I have an issue with my linq query.
There are two tables, Thread
and Post
.
It is built like a forum.
public class Post
{
public int PostID { get; set; }
public int ThreadID { get; set; }
public DateTime Time { get; set; }
public virtual Thread Thread { get; set; }
}
public class Thread
{
public int ThreadID { get; set; }
public string Title { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
Threads:
"1, Thread A"
"2, Thread B"
Posts:
"1, 1, 01.01.15"
"2, 1, 02.01.15"
"3, 1, 03.01.15"
"4, 2, 01.01.15"
Expected result:
"3, 1, 03.01.15"
"4, 2, 01.01.15"
I would like to get all posts grouped by ThreadID
, but I want it to be sorted by the latest post using Time
.
This is my query.
Posts.OrderByDescending(x => x.Time).GroupBy(x => x.ThreadID).Select(x => x.FirstOrDefault());
This return distinct posts, but it finds the oldest post, not the newest.
If I use this code.
Posts.OrderByDescending(x => x.Time)
I get the sorting corerct, but not the distinct posts.
What am I missing?