开发者

LINQ orderby int array index value

开发者 https://www.devze.com 2023-01-31 10:21 出处:网络
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 re

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
          开发者_StackOverflow          {
                        AttributeId = att.ID,
                        DisplayName = att.DisplayName,
                        AttributeName = att.Name
                    };

        return query.ToList();
    }
}


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
};


Why don't you join:

public List BuildTable(int[] attributeIds)
{
    using (var dc = new MyDC())
    {
        var query = from attID in attributeIds
                    join att in dc.DC.Ecs_TblAttributes
                    on attID equals att.ID
                    select new Common.Models.Attribute
                           {
                               AttributeId = attID,
                               DisplayName = att.DisplayName,
                               AttributeName = att.Name
                           };
         return query.ToList();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消