简体   繁体   English

C#和LINQ:通过嵌套查询的值对查询进行排序

[英]C# and LINQ: ordering a query by a nested query's value

I'm writing a simple forum in ASP.NET that sits on top of an Entity Framework database in C#. 我正在ASP.NET中编写一个简单的论坛,该论坛位于C#中的Entity Framework数据库之上。

Each Topic object has a navigation property Posts pointing to a collection of Post objects. 每个Topic对象都有一个导航属性Posts指向Post对象的集合。 Each Post object has a property When that indicates when the post was made. 每个Post对象都有一个属性When ,指示发布时间。

Post.Parent is type Topic . Post.Parent是类型Topic Post.Identifier and Topic.Identifier is type Int32 . Post.IdentifierTopic.IdentifierInt32类型。 Only Post has a When property; 只有Post具有When属性; Topic has no such property. Topic没有这种属性。 Topic.Parent is a third type Forum that is referenced by its Identifier . Topic.Parent是其Identifier所引用的第三类Forum

My problem is this: I can't seem to find a way to sort all Topic objects by the last post made in each topic. 我的问题是:我似乎找不到一种方法来按每个主题的最新文章对所有Topic对象进行排序。 I've tried this: 我已经试过了:

var topics = from t in context.Topics
             from p in a.Posts
             where t.Parent.Identifier == forum.Identifier
             orderby p.When descending
             select t;

But I got duplicate Topic objects and sorting was not by latest post date descending. 但是我得到了重复的Topic对象,并且排序不是按照最新的发布日期降序进行的。

I then tried this: 然后我尝试了这个:

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

It eliminated the duplicate problem, but still no sorting. 它消除了重复的问题,但仍然没有排序。 I even tried 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);

Not sure what to try next; 不知道下一步该怎么做; it seems that these more advanced LINQ expressions escape me. 似乎这些更高级的LINQ表达式使我逃脱了。 Any ideas? 有任何想法吗?

This should work: 这应该工作:

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;

(assuming a Topic has always one or more Post ) (假设一个Topic总是有一个或多个Post

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM