LINQ orderby int数组索引值(LINQ orderby int array index value)
使用LINQ我想按传入的int数组索引排序。
所以在下面的代码中,attribueIds是我的int数组。 我正在使用该数组中的整数作为where子句,但我希望结果按照它们在数组中的顺序排列。
public List BuildTable(int[] attributeIds) { using (var dc = new MyDC()) { var ordering = attributeIds.ToList(); var query = from att in dc.DC.Ecs_TblAttributes where attributeIds.Contains(att.ID) orderby(ordering.IndexOf(att.ID)) select new Common.Models.Attribute { AttributeId = att.ID, DisplayName = att.DisplayName, AttributeName = att.Name }; return query.ToList(); } }Using LINQ I would like to sort by the passed in int arrays index.
So in the code below attribueIds is my int array. I'm using the integers in that array for the where clause but I would like the results in the order that they were in while in the array.
public List BuildTable(int[] attributeIds) { using (var dc = new MyDC()) { var ordering = attributeIds.ToList(); var query = from att in dc.DC.Ecs_TblAttributes where attributeIds.Contains(att.ID) orderby(ordering.IndexOf(att.ID)) select new Common.Models.Attribute { AttributeId = att.ID, DisplayName = att.DisplayName, AttributeName = att.Name }; return query.ToList(); } }最满意答案
我建议改为从attributeIDs数组中选择。 这将确保您的商品无需排序即可正确订购。
代码应该是这样的:
var query = from id in attributeIds let att = dc.DC.Ecs_TblAttributes.FirstOrDefault(a => a.ID == id) where att != null select new Common.Models.Attribute { AttributeId = att.ID, DisplayName = att.DisplayName, AttributeName = att.Name };I would recommend selecting from the attributeIDs array instead. This will ensure that your items will be correctly ordered without requiring a sort.
The code should go something like this:
var query = from id in attributeIds let att = dc.DC.Ecs_TblAttributes.FirstOrDefault(a => a.ID == id) where att != null select new Common.Models.Attribute { AttributeId = att.ID, DisplayName = att.DisplayName, AttributeName = att.Name };更多推荐
发布评论