我有两个表:反馈和评论。一个反馈可以有很多评论。基本上是简单的父子关系。
我有一个页面可以列出所有反馈和相关评论,如下所示:
Feedback A Comment A1 Comment A2 Feedback B Comment B1 Feedback C (note: no comments)
Each feedback and comments have a created date. At the moment I order by feedback date and then comment date so I always have the newest feedback in the top and then all comments after that.
What I'm trying to achieve is: when a new comment is added to a feedback this feedback should be displayed in the top, no matter how old the feedback is or if a feedback is added without comments this feedback should now be the first item in the list. Let's say a comment is added to Feedback B and after that a new feedback with no comments is added, then my list would look like this:
Feedback D (this is the new feedback) Feedback B Comment B1 Comment B2 (this is the new comment) Feedback A Comment A1 Comment A2 Feedback C (note: no comments)
Now Feedback D would be in the top of the list because it has the newest date of all feedback and comments and Feedback B would be second as it has Comment B2 which would have the second newest date.
This is my code so far:
_repositories.Feedback
.Include(f => f.Comments)
.OrderByDescending(f => f.PublishedDate);
我想要的是修改 .OrderByDescending(f => f.PublishedDate) 以获得正确的顺序。这甚至可能吗?
最佳答案
为每个反馈选择最后评论日期并按它们排序:
_repositories.Feedback
.Include(f => f.Comments)
.OrderByDescending(f =>
f.Comments
.Select(c => (DateTime?)c.PublishedDate)
.OrderByDescending(c => c)
.FirstOrDefault() ?? f.PublishedDate
)
.ThenByDescending(f => f.PublishedDate);
关于c# - parent 和 child 的 Linq 顺序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32196093/