2

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

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 查询,它将返回所有线程,按最新发布顺序排序。假设一个实体框架 DbContext 带有Threadsand Posts,如何编写它?分组很简单:

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
4

2 回答 2

4

你可以使用:

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如果您希望首先使用最近发布的线程订购线程,则显然使用。

于 2012-04-12T11:36:08.157 回答
0

你也可以试试:

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;
于 2012-04-12T11:55:18.820 回答