C# 如何按照我提供的ID顺序从Linq查询中获得结果?

C# 如何按照我提供的ID顺序从Linq查询中获得结果?,c#,linq,C#,Linq,我希望按照向查询传递ID的顺序从Linq返回查询结果。所以它看起来像这样: var IDs = new int [] { 5, 20, 10 } var items = from mytable in db.MyTable where IDs.Contains(mytable.mytableID) orderby // not sure what to do here select mytable; 我希望得到的物品的顺

我希望按照向查询传递ID的顺序从Linq返回查询结果。所以它看起来像这样:

var IDs = new int [] { 5, 20, 10 }

var items = from mytable in db.MyTable
            where IDs.Contains(mytable.mytableID)
            orderby // not sure what to do here
            select mytable;
我希望得到的物品的顺序是
id
(5,20,10)


(注意,这与类似,但我希望在Linq而不是SQL中执行)

这应该适用于Linq to对象;但我不确定它是否适用于LINQ to SQL:

var ids = new int [] { 5, 20, 10 };

var result = from item in items
             where Array.IndexOf(ids, item.Id) >= 0
             orderby Array.IndexOf(ids, item.Id)
             select item;

我只需要在SQL查询之外执行它。在这种情况下,在SQL Server上完成这项工作实际上没有任何好处

var items = (from mytable in db.MyTable
             where IDs.Contains(mytable.mytableID)
             select mytable)
            .ToArray()
            .OrderBy(x => Array.IndexOf(ids, x.mytableID));

@阿贝-谢谢你的关注!愚蠢的拼写检查软件