Zachary Scott
Zachary Scott

Reputation: 21182

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 Products.OrderBy() and order by myField, what would the Expression look like?

Products.OrderBy( p => p.Prices.SelectMany( ??

Upvotes: 1

Views: 1037

Answers (2)

Saeed Amiri
Saeed Amiri

Reputation: 22555

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))

Upvotes: 1

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47048

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 )

Upvotes: 1

Related Questions