Entity Framework 4 / Linq: How to OrderBy() a hierarchical Entity?
I have a ViewModel carved from several Entity relations:
Products[].Prices[].Others[].myField
How do I order Products[] by the nested myField? When I do the Where clause, it's like this:
Products.Where( p => p.Prices.Any( q => q.Others.Any( r => r.myField == 4)));
So if I wanted to P开发者_如何转开发roducts.OrderBy() and order by myField, what would the Expression look like?
Products.OrderBy( p => p.Prices.SelectMany( ??
As you have several prices below your product you need to select which one to sort on, like
Products.OrderBy( p => p.Prices.First().Others.First().myField )
or if you want to order by the highest price
Products.OrderBy( p => p.Prices.OrderByDescending(price => price.Value).First().Others.First().myField )
I assume prices has a field Value
which is primary type or Comparable type so you have:
Products.OrderBy( p => p.Prices.Average(x=>x.Value))
or
Products.OrderBy( p => p.Prices.Min(x=>x.Value))
精彩评论