I'm not into queries and databases that much but you can do this quite quickly with just doing C# tricks
var ids = new int[]{5, 1, 8, 2, 3};
var dict = ids.Select((id, i) => new { Index = i, Id = id })
.ToDictionary(x => x.Id, x => x.Index);
var items = Db.Items
.Where(x => ids.Contains(x.Id))
.OrderBy(x => dict[x.Id]);
I can't tell how it will get translated into a database query
I haven't tested it, but here'e a version without OrderBy
, but less space-efficient (it might actually be slower):
var ids = new int[]{5, 1, 8, 2, 3};
var temp = Db.Items
.Where(x => ids.Contains(x.Id))
.ToLookup(x => x.Id);
var tempList = new List<IGrouping<int, Item>>();
for(int i = 0; i < ids.Length; i++)
{
tempList.Add(temp[ids[i]]);
}
var items = tempList.SelectMany(x => x);
There is also another way - simply do a reverse join:
var ids = new int[]{5, 1, 8, 2, 3};
var items = from id in ids
join item in Db.Items
on id equals item.Id
select item;
This will result in a query sorted by ids