Linq Order by List <int> Identifiers
I am trying to sort a linq query so that the results are returned in the order of identifiers found in 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 to do this so that nposts returns the results in the order in which npostID exist in List [int]?
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 mistake, I have another suggestion. I am not 100% sure if it will work or not in EF, but try and let me know. There is another idea that I know, but that will not work.
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 npostIDs without an orderby . If the ObjectContext is the same (and maybe if not), you should really be able to do this in a single request. However, it is unclear whether the list of npostIDs or not, so this may 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 a method version of this answer:
IEnumerable<NPost> nposts = repository.NPosts .Where(np => npostIDs.IndexOf(np.NPostID) >= 0) .OrderBy(np => npostIDs.IndexOf(np.NPostID));