C#和LINQ:按嵌套查询的值排序查询

时间:2011-08-22 00:00:04

标签: c# linq tsql entity-framework linq-to-entities

我正在ASP.NET中编写一个简单的论坛,它位于C#中的实体框架数据库之上。

每个Topic对象都有一个导航属性Posts,指向Post个对象的集合。每个Post对象都有一个属性When,用于指示发布帖子的时间。

Post.ParentTopic类型。 Post.IdentifierTopic.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表达式让我感到厌烦。有什么想法吗?

1 个答案:

答案 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

相关问题