Reputation: 616
I have a simple relation like
public class Invoice{
public int Id {get;set;}
ICollection Product Products {get;set;}
}
public class Product {
public int Id {get;set;}
public DateTime ReceptionDate {get;set;}
public virtual Invoice Invoice{get;set;}
}
I want to present invoices ordered by Product ReceptionDate, so the invoice with the most recent Product goes first. I'm also paging the results.
I tried
invoices.OrderByDescending(x => x.Products.Select(y => y.ReceptionDate)).Skip(x).Take(y);
But it's not even a valid query.
Could not find a similar question by searching.
Thanks.
Edit: Also tried Sergey solution but it's too slow, because it calls ToArray() fetching thousands of records from the database.
Upvotes: 0
Views: 315
Reputation: 43959
Try this query:
var query=Products
.GroupBy(g => new { g.Invoice.Id, g.ReceptionDate})
.Select(g => new
{
Id=g.Key.Id
ReceptionDate=g.Key.ReceptionDate
})
.OrderBy(x => x.ReceptionDate)
.ToArray();
Upvotes: 1
Reputation: 9
Maybe you should try this:
invoices.OrderByDescending(x => x.Products.Max(y => y.ReceptionDate));
Upvotes: 0