加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 06:40:06 所属栏目:asp.Net 来源:网络整理
导读:我在ASP.NET MVC中编写简单的论坛. 在类别视图中,我想显示最新的主题. 我的代码按线程添加日期排序: model.ForumThreads = db.ForumThreads .Where(t = t.ForumThreadCategoryId == id) .OrderByDescending(t = t.AddDate) .ToPagedList(page,10); ForumPos
我在ASP.NET MVC中编写简单的论坛.

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

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

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

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

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

解决方法

使用三元if运算符(if?then:else):

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读