ASP.NET MVC - 根据最后的帖子排序论坛帖子

Dav*_*ave 4 linq asp.net asp.net-mvc linq-to-entities entity-framework

我在ASP.NET MVC中编写简单的论坛.

在类别视图中,我想显示最新的主题.

我的代码按线程添加日期排序:

model.ForumThreads = db.ForumThreads
   .Where(t => t.ForumThreadCategoryId == id)
   .OrderByDescending(t => t.AddDate)
   .ToPagedList(page, 10);
Run Code Online (Sandbox Code Playgroud)

ForumPost模型具有ForumThread模型的外键.

问题是:如何按最后一篇文章对线程进行排序,但如果没有帖子则按线程添加日期排序.

teo*_*kot 5

使用三元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);
Run Code Online (Sandbox Code Playgroud)