I am trying to sort a linq query so that the results are returned in the order of the IDs found in the List[int]. Here is my current code that returns them just fine, but not sorted.
IEnumerable<NPost> nposts;
List<int> npostIDs = (from tc in db.TopComs
where tc.Type == "Comments"
select tc.NPostID).ToList();
nposts = from np in repository.NPosts
where npostIDs.Contains(np.NPostID)
select np;
How can I have it so that nposts returns the results in the order in which npostIDs exists in the List[int]?
Update
Based on your error, I’ve got another suggestion. I’m not 100% sure if it will work or not in EF, but give it a try and let me know. There’s one other idea I have that I know would work but it’s not going to perform as well.
This will maintain the order of the
npostIDswithout anorderbyclause. If theObjectContextis the same (and maybe if it’s not), you should actually be able to do it in a single query. However, it’s not clear if you are caching thenpostIDslist or not, so this might not be an option. Anyway, here: