How do I get results from a Linq query in the order of IDs that I provide?
I'm looking to get query results back from Linq in the order that I pass IDs to the query. So it would look something like this:
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;
I'm hoping to get items in the order of IDs
(5, 20, 10).
(Note this is similar to this question, but I would like 开发者_开发技巧to do it in Linq instead of SQL)
I would just do it outside of the SQL query. There's really no benefit to getting it done on the SQL Server in this case.
var items = (from mytable in db.MyTable
where IDs.Contains(mytable.mytableID)
select mytable)
.ToArray()
.OrderBy(x => Array.IndexOf(ids, x.mytableID));
This should work with LINQ-to-objects; I'm not sure if it does with LINQ-to-SQL though:
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;
精彩评论