我正在 ASP.NET MVC 中编写简单的论坛。
在类别 View 中,我想显示最新的线程。
我按线程添加日期排序的代码:
model.ForumThreads = db.ForumThreads
.Where(t => t.ForumThreadCategoryId == id)
.OrderByDescending(t => t.AddDate)
.ToPagedList(page, 10);
ForumPost 模型具有 ForumThread 模型的外键。
问题是:
如何按最后一个帖子对主题进行排序,但如果没有帖子,则按主题添加日期排序。
最佳答案
使用三元if
运算符(如果 ?
然后 :
否则):
model.ForumThreads = db.ForumThreads
.Where(t => t.ForumThreadCategoryId == id)
.OrderByDescending(t => t.ForumPosts.Any() //if
? t.ForumPosts.Max(x=>x.AddDate) //then by post add date
: t.AddDate) //else like you already do
.ToPagedList(page, 10);
关于ASP.NET MVC - 根据上一篇文章对论坛主题进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39036356/