Need some help ordering a Linq result
-
21-08-2019 - |
Question
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?
Solution
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.