tags:

views:

149

answers:

1

Hi folks,

I have some Linq code, that works fine. It retrieves a list of board posts ordered by the most recent.

The catch here is the order by ... it orders by the most recent COMMENTS. So if a board post just got a comment, then it will be up the top of the list (ie. most recent).

kewl ... but what about new board posts that just got created? They are listed down the bottom, because they have NO comments :( It's like i want to say "order by most recent comments .. but if u have no comment, then its by your board post create date)".

here's my linq...

boardPostList = (from bp in db.tblBoardPosts.Where(whereClause)
    orderby (from bc in bp.tblBoardComments
    orderby bc.DateModified descending
    select bc.DateModified).First() descending
    select bp).ToPagedList(pageNumber, numberOfResults);

Does anyone have any suggestions?

A: 

Is there any reason you can't update a field in tblBoardPosts whenever a comment is posted to it? Keep the "posted or last comment" date, then you've got a much simpler query, and one which doesn't need to scan every comment in the system to work out what to do.

Having said that, this query might work, if your DateModified field is nullable:

boardPostList = (from bp in db.tblBoardPosts.Where(whereClause)
    orderby ((from bc in bp.tblBoardComments
    orderby bc.DateModified descending
    select bc.DateModified).FirstOrDefault() ?? bp.DateModified) descending
    select bp).ToPagedList(pageNumber, numberOfResults);

If it's just a straight DateTime column, the result of FirstOrDefault is still a DateTime which would be non-nullable... You could try:

boardPostList = (from bp in db.tblBoardPosts.Where(whereClause)
    let lastComment = bp.tblBoardComments
                        .OrderByDescending(bc => bc.DateModified)
                        .FirstOrDefault()
    let lastModified = (lastComment == null 
                        ? bp.DateModified 
                        : lastComment.DateModified) 
    orderby lastModified descending
    select bp).ToPagedList(pageNumber, numberOfResults);

It's pretty hideous though, and may not translate into SQL properly. I would certainly try to change to a scheme where the post itself keeps track of it.

Jon Skeet
Heya Jon :) heh .. i tried the first suggestion while i was waiting for some answers, but it wouldn't compile because the DateTime is not null, as u correctly pointed out. I had no idea how to get to the second suggestion, u made... which works. So thanks :) (BTW, schema change is now pencilled in, btw. Gotta do it right...)
Pure.Krome
That works? I'm somewhat surprised, to be honest. I guess the LINQ to SQL query translator is pretty smart :)
Jon Skeet
yeah .. it actually did :)
Pure.Krome