2012-04-12 83 views
2

一个LINQ分组查询我有这些简单的类问题:排序基于群

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与ThreadsPosts,如何编写它?分组很简单:

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

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

编辑 - 解决方案基于容斯回答:

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

你可以使用:

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如果你想先用大部分的最近发布的线程下令线程。

+0

非常感谢您!我通过添加一个“从p.Posts中的p”开始工作,然后进行分组和排序。 – ciscoheat 2012-04-12 11:45:15

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;