按平均值降序对 ICollection 进行排序(包括可为空值)
给出以下代码:
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; }
}
假设我有数据库中每本书的列表:
var books; // List<Book>
我想向用户显示按平均评论排序的书籍。理想情况下,图书列表的平均评论应位于顶部,并按降序排列。鉴于我在评论中的总体评分为可为空的整数,因此有些书不会有评论,更不用说总体评分了。我在排序这些数据时遇到困难,我几乎尝试了以下所有组合:
books.OrderByDescending(b => b.Reviews.Average(a => a.Overall));
是否可以在不创建第二个列表的情况下对我的列表进行排序以获得类似:
- Book A (4.5/5)
- Book B (4.3/5)
- Book C (3.9/5)
- 书 D (3.5/5)
- 书 E (-/5)
- 书 F (-/5)
提前致谢。
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; // 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你应该能够使用这个:
You should be able to use this:
感谢 TheCodeKing 为我指明了正确的方向。这是解决问题的方法:
Thank you TheCodeKing for point me in the right direction. Here is what fixed the problem: