根据组对 LINQ 分组查询进行排序

本文关键字:查询 排序 LINQ | 更新日期: 2023-09-27 18:30:48

我对这些简单的类有问题:

public class Thread
{
    public string Title { get; set; }
    public ICollection<Post> Posts { get; set; }
}
public class Post
{
    public DateTime Posted { get; set; }
    public string Text { get; set; }
}

我想要一个 LINQ 查询,它将返回所有线程,按最新的后顺序排序。假设一个具有ThreadsPosts的实体框架 DbContext,如何编写它?分组很简单:

from t in Threads
group t.Posts by t into tg
select tg.Key;

但是如何根据最新的Post.Posted对线程进行排序?

编辑 - 基于 Jons 答案的解决方案:

from t in Threads
from p in t.Posts
group p by t into tg
orderby tg.Max(p => p.Posted) descending 
select tg.Key

根据组对 LINQ 分组查询进行排序

您可以使用:

from t in Threads
group t.Posts by t into tg
orderby tg.Max(post => post.Posted) // Order by the latest post per thread
select tg.Key;

显然,如果您希望将线程与最近发布的线程一起排序,请使用descending

您也可以尝试:

var orderedThread1 = from t in threads
                     from p in t.Posts
                     orderby p.Posted ascending 
                     select t;
var orderedThread2 = from t in threads
                     group t.Posts by t
                     into tp
                     orderby tp.Max(posts => posts.Max(p => p.Posted))
                     select tp.Key;