我正在ASP.NET中编写一个简单的论坛,它位于C#中的实体框架数据库之上。
每个Topic
对象都有一个导航属性Posts
,指向Post
个对象的集合。每个Post
对象都有一个属性When
,用于指示发布帖子的时间。
Post.Parent
是Topic
类型。 Post.Identifier
和Topic.Identifier
的类型为Int32
。只有Post
具有When
属性; Topic
没有此类财产。 Topic.Parent
是第三种类型Forum
,由Identifier
引用。
我的问题是:我似乎找不到通过每个主题中的 last 帖子对所有Topic对象进行排序的方法。我试过这个:
var topics = from t in context.Topics
from p in a.Posts
where t.Parent.Identifier == forum.Identifier
orderby p.When descending
select t;
但我得到了重复的Topic
个对象,并且按最新的发布日期降序排序不。
然后我尝试了这个:
var topics = (from t in context.Topics
let lastPost =
(from p in context.Posts
where p.Parent.Identifier == a.Identifier
orderby p.When descending
select p).FirstOrDefault().When
where t.Parent.Identifier == forum.Identifier
orderby lastPost descending
select t).Distinct();
它消除了重复的问题,但仍然没有排序。我甚至试过a suggestion from another question:
var topics = (from t in context.Topics
let posts = context.Posts.Where(p => p.Parent.Identifier == t.Identifier)
let lastPost = posts.OrderByDescending(p => p.When).FirstOrDefault()
where t.Parent.Identifier == forum.Identifier
orderby lastPost.When descending
select t);
不确定接下来要尝试什么;似乎这些更高级的LINQ表达式让我感到厌烦。有什么想法吗?
答案 0 :(得分:4)
这应该有效:
var topics = from t in context.Topics
where t.Parent.Identifier == forum.Identifier
let lastPost = t.Posts.OrderByDescending(p => p.When).First()
orderby lastPost.When descending
select t;
(假设Topic
始终有一个或多个Post
)