Linq order from parent and child

I have two tables: reviews and comments. Feedback can have many comments. Basically, this is a simple parent child relationship.

I have a page to list all reviews and related comments as follows:

Feedback A
Comment A1
Comment A2

Feedback B
Comment B1

Feedback C (note: no comments)

Each feedback and comment has a created date. At the moment, I am ordering the feedback date and then the comment date, so I always have the latest feedback at the top, and then all the comments after that.

What I'm trying to achieve is this: when a new comment is added to the comments, this feedback should be displayed at the top, no matter how old the feedback or feedback without comments is added, this feedback should now be The first item in the list. Let's say a comment is added to Feedback B, and after that a new feedback is added without comments, then my list will look like this:

Feedback D (this is the new feedback)

Feedback B
Comment B1
Comment B2 (this is the new comment)

Feedback A
Comment A1
Comment A2

Feedback C (note: no comments)

Now the feedback D will be at the top of the list, because it has the newest date of all reviews and comments, and Feedback B will be the second, because it contains comment B2, which will have the second most recent date.

This is my code:

_repositories.Feedback
.Include(f => f.Comments)
.OrderByDescending(f => f.PublishedDate);

I would like to change

.OrderByDescending (f => f.PublishedDate)
to get the correct order. Is it possible?
+4
source share
1 answer

Select the last comment date for each feedback and sort them:

_repositories.Feedback
.Include(f => f.Comments)
.OrderByDescending(f => 
    f.Comments
    .Select(c => (DateTime?)c.PublishedDate)
    .OrderByDescending(c => c)
    .FirstOrDefault() ?? f.PublishedDate
)
.ThenByDescending(f => f.PublishedDate);
+2
source

All Articles