我对这些简单的类有疑问:
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查询,它将返回所有线程,按最新的顺序排序。假设有Threads
和Posts
的实体框架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
答案 0 :(得分: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
。
答案 1 :(得分: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;