ASP.NET MVC - Sort forum topics by last post

I am writing a simple forum in ASP.NET MVC.

In the category view, I want to show the latest streams.

My code, sorted by the date the stream was added:

model.ForumThreads = db.ForumThreads
   .Where(t => t.ForumThreadCategoryId == id)
   .OrderByDescending(t => t.AddDate)
   .ToPagedList(page, 10);

The ForumPost model has a foreign key for the ForumThread model.

The problem is this: How to sort topics by last post, but if there are no posts, sort by topic add a date.

+4
source share
1 answer

Use the ternary operator if(if ?, then :else):

model.ForumThreads = db.ForumThreads
   .Where(t => t.ForumThreadCategoryId == id)
   .OrderByDescending(t => t.ForumPosts.Any() //if
                         ? t.ForumPosts.Max(x=>x.AddDate) //then by post add date
                         : t.AddDate) //else like you already do
   .ToPagedList(page, 10);
+5
source

Source: https://habr.com/ru/post/1651772/


All Articles