Sorting an ICollection descending by average including nullable values
Given the following code:
class Book {
public int ID { get; set; }
public string Name { get; set; }
public ICollection<Review> Reviews { get; set; }
}
class Review {
public int ID { get; set; }
public int? Overall { get; set; }
public string Comment { get; set; }
}
And assuming I have a list of every book in the database:
var books; /开发者_JAVA技巧/ List<Book>
I would like to show the user the books ordered by the average review. Ideally, the list of books would have the highest average review at the top and sort descending. Given I have the overall rating in Review as a null-able integer, some books will not have reviews, let alone an overall score. I'm having difficulty sorting this data, I've tried seemingly every combination of:
books.OrderByDescending(b => b.Reviews.Average(a => a.Overall));
Is it possible to sort my list without creating a second list to get something like:
- Book A (4.5/5)
- Book B (4.3/5)
- Book C (3.9/5)
- Book D (3.5/5)
- Book E (-/5)
- Book F (-/5)
Thanks in advance.
You should be able to use this:
books.OrderByDescending(b =>
(b.Reviews == null) ? 0:b.Reviews.Average(r => r.Overall??0));
Thank you TheCodeKing for point me in the right direction. Here is what fixed the problem:
books.OrderByDescending(b => b.Reviews.Count() == 0 ? 0 : b.Reviews.Average(r => r.Overall ?? 0));
精彩评论