Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of entities by list of id's - IN ORDER

See this question/answer: Entity Framework: Get all rows from the table for the ids in list

Now my question: I would like to get the entities sorted as they are in the list of id's.

I would be dealing with a small list, and don't mind if it's sorted in memory after pulling list from db.

like image 318
mendel Avatar asked Aug 05 '15 22:08

mendel


1 Answers

var result = db.table
  .Where(l => ids.Any(id => id == l.id))
  .ToList()
  .OrderBy(l => ids.IndexOf(l.id));

or

var result = db.table
  .Where(l => ids.Contains(l.id))
  .ToList()
  .OrderBy(l => ids.IndexOf(l.id));

both should work fine.

like image 71
Robert McKee Avatar answered Dec 23 '22 12:12

Robert McKee