I have a problem with these simple classes:
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; }
}
I’d like a LINQ query that will return all Threads, sorted in latest post order. Assuming an Entity Framework DbContext with Threads and Posts, how to write it? Grouping is simple:
from t in Threads
group t.Posts by t into tg
select tg.Key;
But how to sort the Threads based on the latest Post.Posted?
Edit – Solution based on Jons answer:
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
You could use:
Obviously use
descendingif you want the threads ordered with the mostly-recently-posted thread first.