I’m wondering if it is possible to use a lambda expression to order a list of items based on the average value of a nested list of items.
In project terms, I have a list of products that each can have many reviews. I want to order the list of the products based on the average rating from each product’s list of reviews.
I have this:
products = category.Products.OrderBy(i => i.Reviews.Average(x => x.Rating));
This builds without a problem but when I run it, it returns an error that says
Sequence contains no elements
Is it possible to do this with a lambda expression?
Enumerable.Averagethrows theInvalidOperationExceptionbecause the sequence contains no elements since a product has noReviews.You could use
Enumerable.DefaultIfEmpty(customValue):Maybe you want to exclude these products from the result: