tags:

views:

45

answers:

2

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)

+1  A: 

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;
dtb
+1  A: 

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));
Mike