LINQ to Entities question about orderby and null collections.

Posted by Chevex on Stack Overflow See other posts from Stack Overflow or by Chevex
Published on 2011-01-09T05:01:57Z Indexed on 2011/01/09 5:53 UTC
Read the original article Hit count: 267

I am currently developing a forum. I am new to LINQ and EF. In my forum I have a display that shows a list of topics with the most recent topics first.

The problem is that "most recent" is relative to the topic's replies. So I don't want to order the list by the topic's posted date, rather I want to order the list by the topic's last reply's posted date. So that topics with newer replies pop back to the top of the list. This is rather simple if I knew that every topic had at least one reply; I would just do this:

var topicsQuery = from x in board.Topics
                  orderby x.Replies.Last().PostedDate descending
                  select x;

However, in many cases the topic has no replies. In which case I would like to use the topic's posted date instead. Is there a way within my linq query to order by x.PostedDate in the event that the topic has no replies? I'm getting confused by this and any help would be appreciated. With the above query, it breaks on topics with no replies because of the x.Replies.Last() which assumes there are replies. LastOrDefault() doesn't work because I need to access the PostedDate property which also assumes a reply exists.

Thanks in advance for any insight.

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ