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]?
IEnumerable<NPost> nposts = from np in repository.NPosts
let index = npostIDs.IndexOf(np.NPostID)
where index >= 0
orderby index ascending
select np;
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.
IEnumerable<NPost> nposts = from npostID in npostIDs.AsQueryable()
join np in repository.NPosts
on npostID equals np.NPostID
select np;
This will maintain the order of the npostIDs
without an orderby
clause. If the ObjectContext
is 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 the npostIDs
list or not, so this might not be an option. Anyway, here:
IEnumerable<NPost> nposts = from tc in db.TopComs
where tc.Type == "Comments"
join np in repository.NPosts
on tc.NPostID equals np.NPostID
select np;
The accepted answer is correct, I just wanted to provide the method version of this answer:
IEnumerable<NPost> nposts = repository.NPosts
.Where(np => npostIDs.IndexOf(np.NPostID) >= 0)
.OrderBy(np => npostIDs.IndexOf(np.NPostID));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With