Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Order by List<int> of IDs given

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]?

like image 320
Adam Frick Avatar asked Oct 01 '12 14:10

Adam Frick


2 Answers

IEnumerable<NPost> nposts = from np in repository.NPosts
                            let index = npostIDs.IndexOf(np.NPostID) 
                            where index >= 0
                            orderby index ascending
                            select np;

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.

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;
like image 84
smartcaveman Avatar answered Oct 25 '22 13:10

smartcaveman


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));
like image 6
DLeh Avatar answered Oct 25 '22 14:10

DLeh