Wednesday, January 23, 2019

Inject an ordering into a .SelectMany in C#!

private IQueryable<Cat> GetCatsForUser(int id)
{
   return _context.Users.Where(u => u.Id == id).SelectMany(u => u.Cats).Distinct();
}

 
 

...becomes:

private IQueryable<Cat> GetCatsForUser(int id)
{
   return _context.Users.Where(u => u.Id == id).SelectMany(u =>
         u.Cats).Distinct().OrderByDescending(r => r.BirthDay);
}

 
 

Something NOT to do is:

private IQueryable<Cat> GetCatsForUser(int id)
{
   return _context.Users.Where(u => u.Id == id).SelectMany(u =>
         u.Cats.OrderByDescending(r => r.BirthDay)).Distinct();
}

 
 

Distinct is for removing dupes.

No comments:

Post a Comment