LINQ orderby int数组索引值(LINQ orderby int array index value)

编程入门 行业动态 更新时间:2024-10-26 22:18:21
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 };

更多推荐

本文发布于:2023-07-29 20:15:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1319447.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   索引   orderby   LINQ   int

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!