2012-04-12 120 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;