2016-08-19 33 views
4

我在ASP.NET MVC中編寫簡單的論壇。ASP.NET MVC - 根據最後發表的帖子排序論壇主題

類別視圖我想顯示最新的主題。

我的代碼由線程添加日期排序:

model.ForumThreads = db.ForumThreads 
    .Where(t => t.ForumThreadCategoryId == id) 
    .OrderByDescending(t => t.AddDate) 
    .ToPagedList(page, 10); 

ForumPost模型有外鍵ForumThread模型。

問題是: 如何按最後發帖排序帖子,但如果沒有帖子,則按線程添加日期排序。

回答

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); 
+0

謝謝你,小的修改和它的作品! – Dave

相關問題