I'm working with entity framework database and I want to populate my dropdownlist from a table but in right order.
Right now i'm using the code:
var databaseList = from p in db.TECHNICAL_SKILLS
where p.skill_type == "Database"
select new EmployeeTechnicalSkillInfo
{
TechnicalSkillId = p.technical_skill_id,
SkillType = p.skill_type,
SkillName = p.skill_name
};
List<object> sDataValue = new List<object>();
sDataValue.Add("- Select -");
sDataValue.Remove("Other");
foreach (var vData in databaseList)
{
sDataValue.Add(vData.SkillName);
}
sDataValue.Add("Other");
DropDownListDB.DataSource = sDataValue.ToArray();
DropDownListDB.DataBind();
This is the Solution
var databaseList = from p in db.TECHNICAL_SKILLS
where p.skill_type == "Database"
orderby p.skill_name != "Other" descending, p.skill_name
select new EmployeeTechnicalSkillInfo
{
TechnicalSkillId = p.technical_skill_id,
SkillType = p.skill_type,
SkillName = p.skill_name
};
Remove the entry -Select- from the list and append it as first item to your List<object>:
List<object> sDataValue = new List<object>();
sDataValue.Add("-Select-");
foreach (var vData in databaseList){}
would be the easiest way, I assume.
EDIT
then you will use if/else, maybe and
foreach (var vData in databaseList){} //fill your list
sDataValue.Add("-Other-");
You could add a "section id" to your database: 0 for "-Select-", 2 for "Other", 1 for the rest. Then sort on 1) section ID, 2) name.
But it would be best not to store that "-Select-" at all (it doesn't represent a valid value) and add it in the correct spot after the databind.
Just do this:
Remove -Select- and Other from databaseList like this:
var databaseList = from p in db.TECHNICAL_SKILLS
where p.skill_type == "Database"
&& p.skill_name.ToLower() !="other"
&& p.skill_name.ToLower() !="-select-"
select new EmployeeTechnicalSkillInfo
{
TechnicalSkillId = p.technical_skill_id,
SkillType = p.skill_type,
SkillName = p.skill_name
};
and then do this:
DropDownListDB.DataSource = sDataValue.ToArray().OrderBy(s=>s);
DropDownListDB.Items.Insert(0, "-Select-");
DropDownListDB.Items.Add("Other");
if you must bring -Select- and Other field from database, binding them to the DropDownList and then removing them and again inserting them at appropriate location is little expensive.
You simply don't pick those two rows from the database. it will be more efficient.
You can try play with orderby with boolean value
orderby p.skill_name != "Other" descending, p.skill_name
In your code =>
var databaseList = from p in db.TECHNICAL_SKILLS
where p.skill_type == "Database"
orderby p.skill_name != "Other" descending, p.skill_name
select new EmployeeTechnicalSkillInfo
{
TechnicalSkillId = p.technical_skill_id,
SkillType = p.skill_type,
SkillName = p.skill_name
};
List<object> sDataValue = new List<object>();
sDataValue.Add("- Select -");
foreach (var vData in databaseList)
{
sDataValue.Add(vData.SkillName);
}
DropDownListDB.DataSource = sDataValue.ToArray();
DropDownListDB.DataBind();
Related
I have a list of objects and alist of integers. Objects have property called exists.
public bool exists;
I need to join this two lists using left join and if ids exist in two lists, then set "exists" property to true;
I prepred dotnetfiddle example:
https://dotnetfiddle.net/sE1RIl
Expected result is (pseudocode):
Item1.exists = true;
Item2.exists = true;
Item3.exists = false;
Probably I will need to add more left joins later, so I am interested in the most flexible way to achieve that.
You can map your properties using select statement:
IEnumerable<Item> items = new List<Item>()
{
new Item (){id =1, name = "Item1"},
new Item (){id =2, name = "Item2"},
new Item (){id =3, name = "Item3"}
};
List<int> ids = new List<int>() {1,2};
var param_1 = true;
var param_2 = false;
var param_3 = true;
var listOfItems = from item in items
join id in ids on item.id equals id
into result
from r in result.DefaultIfEmpty()
select new Item
{
id = item.id,
name = item.name,
exists = (param_1 == true) ? true
: (param_2 == false && param_3 == true) ? false
: true
};
How to set selected true from contains list string in linq ???
I want to set selected true if some field is same from variabel list string. this is my code for my case.
string detail = Request.QueryString["detail"];
List<string> KdUser = new List<string>();
if (detail != null) {
KdUser = (from u in db.TUserSelecteds where u.detail_guid_edis == new Guid(detail) select u.kode_user).ToList();
}
// KdUser = [0]U002,[1]U001,[2]U003
List<SelectListItem> items = (from us in db.Users
where us.ApplicationId == "TMS-APP-03" && us.IsActive == 1
orderby us.NamaKaryawan
select new SelectListItem()
{
Text = us.NamaKaryawan,
Value = us.KodeUser
//Selected = true => If (Value Contains KdUser)
}).ToList();
I hope you understand what i mean. thanks
List<SelectListItem> items = (from us in db.Users
where us.ApplicationId == "TMS-APP-03" && us.IsActive == 1
orderby us.NamaKaryawan
select new SelectListItem()
{
Text = us.NamaKaryawan,
Value = us.KodeUser
Selected = KdUser.Contains(us.KodeUser)
}).ToList();
Having:
Initialize an anonymouse collection (I would send it as json)
var myCollection = new[]
{
new
{
Code = 0,
Name = "",
OtherAttribute = ""
}
}.ToList();
myCollection.Clear();
And get the data.
myCollection = (from iPeople in ctx.Person
join iAnotherTable in ctx.OtherTable
on iPeople.Fk equals iAnotherTable.FK
...
order by iPeople.Name ascending
select new
{
Code = iPeople.Code,
Name = iPeople.Name,
OtherAttribute = iAnotherTable.OtherAtribute
}).ToList();
I want to add an Identity column, I need the collection ordered and a counted from 1 to collection.count. Is for binding this counter to a Column in a table (jtable).
var myCollection = new[]
{
new
{
Identity = 0,
Code = 0,
Name = "",
OtherAttribute = ""
}
}.ToList();
myCollection = (from iPeople in ctx.Person
join iAnotherTable in ctx.OtherTable
on iPeople.Fk equals iAnotherTable.FK
...
order by iPeople.Name ascending
select new
{
Identity = Enum.Range(1 to n)//Here I donĀ“t know how to do; in pl/sql would be rownum, but in Linq to SQL how?
Code = iPeople.Code,
Name = iPeople.Name,
OtherAttribute = iAnotherTable.OtherAtribute
}).ToList();
If you are using linq to entities or linq to sql, get your data from the server and ToList() it.
Most likely this answer will not translate to sql but I have not tried it.
List<string> myCollection = new List<string>();
myCollection.Add("hello");
myCollection.Add("world");
var result = myCollection.Select((s, i) => new { Identity = i, Value = s }).ToList();
As Simon suggest in comment, that could would look like below:
int counter = 0; //or 1.
myCollection = (from iPeople in ctx.Person
join iAnotherTable in ctx.OtherTable
on iPeople.Fk equals iAnotherTable.FK
...
order by iPeople.Name ascending
select new
{
Identity = counter++,
Code = iPeople.Code,
Name = iPeople.Name,
OtherAttribute = iAnotherTable.OtherAtribute
}).ToList();
Is there any problem in executing this kind of code?
As Simon stated in his comments, consider the following, albeit contrived, example:
int i = 0;
var collection = Enumerable.Range(0, 10).Select(x => new { Id = ++i });
One solution that helped me to achieve the same goal:
Create a separate Function like this:
private int getMaterialOrder(ref int order)
{
return order++;
}
Then call it in your linq query like:
...
select new MaterialItem() { Order=getMaterialOrder(ref order),
...
I am trying to add an item to an IEnumerable SelectList. I have an initial query that populates my list, I then have a query to check to see if an item called "INFORMATIONAL" exists. If not, I need to add it to the list returned from my initial query. Here is my code. It does not like list.Add(newItem). Any assistance would be appreciated. Thanks
public IEnumerable<SelectListItem> GetCategoriesByAccountID(string AccountID)
{
IEnumerable<SelectListItem> list = null;
using (var context = new AMPEntities())
{
// Queries DB for list of categories by AccountID
var query = (from ca in context.CustomAlerts
where ca.AccountID == AccountID
orderby ca.AlertCategory
select new SelectListItem { Text = ca.AlertCategory, Value = ca.AlertCategory }).Distinct();
list = query.ToList();
// Checks list to see if "INFORMATIONAL" already exists
var item = (from l in list
where l.Value == "INFORMATIONAL"
select new SelectListItem { Text = l.Text, Value = l.Value }).FirstOrDefault();
// If "INFORMATIONAL" is not present add it to list
if (item == null)
{
var newItem = new SelectListItem { Text = "INFORMATIONAL", Value = "INFORMATIONAL" };
list.Add(newItem);
}
}
return list;
}
The problem is that your variable is of type IEnumerable<SelectListItem>. Either change it to List<SelectListItem> or use another variable.
public IEnumerable<SelectListItem> GetCategoriesByAccountID(string AccountID)
{
List<SelectListItem> list = null;
using (var context = new AMPEntities())
{
// Queries DB for list of categories by AccountID
var query = (from ca in context.CustomAlerts
where ca.AccountID == AccountID
orderby ca.AlertCategory
select new SelectListItem { Text = ca.AlertCategory, Value = ca.AlertCategory }).Distinct();
list = query.ToList();
// Checks list to see if "INFORMATIONAL" already exists
var item = (from l in list
where l.Value == "INFORMATIONAL"
select new SelectListItem { Text = l.Text, Value = l.Value }).FirstOrDefault();
// If "INFORMATIONAL" is not present add it to list
if (item == null)
{
var newItem = new SelectListItem { Text = "INFORMATIONAL", Value = "INFORMATIONAL" };
list.Add(newItem);
}
}
return list;
}
Essentially, you cannot, because IEnumerable does not necessarily represent a collection to which items can be added. See this question on SO.
How can I add an item to a IEnumerable<T> collection?
Here is something I came up with that might be helpful to someone. Maybe even me at a later date. Take a look at the last line of code.
CostCenterHeaders CostHeaders = CostCenterHeaders.GetCostCenterHeaders(ClientNumber);
List<SelectListItem> Level1Header = new List<SelectListItem>();
if (CostHeaders.Level1Heading !=null)
{
Level1Header.Add(new SelectListItem { Text = "All " + CostHeaders.Level1Heading + " Centers", Value = "" });
List<HierarchyLevel> HierarchyLevels = HierarchyLevel.GetHierarchyByLevel(ClientNumber);
Level1Header.AddRange(HierarchyLevels.Select(x => new SelectListItem() { Value = x.LevelID, Text = x.LevelDescr }).ToList());
}
I have a Linq query as below.
var DataSource = from m in product
select new { Class = m.Class, Id = (new Make(m.Id)).ProductName};
I instantiate a class called Make and fetch the ProductName based on the Id.
Some of the Id's are 0.
Is there a way I can exclude all the Id's that are 0?
Sure, just do this:
var DataSource = from m in product
where m.Id != 0
select new
{
Class = m.Class,
Id = (new Make(m.Id)).ProductName
};
You're looking for the where clause:
where m.Id != 0
var DataSource = from m in product
where m.Id != 0
select new
{
Class = m.Class,
Id = (new Make(m.Id)).ProductName
};
Try this:
var DataSource = from m in product
where m.Id != 0
select new { Class = m.Class, Id = (new Make(m.Id)).ProductName};