Dave Dave - 3 months ago 20
ASP.NET (C#) Question

ASP.NET MVC - Sorting forum threads depending on last post

I am writing simple forum in ASP.NET MVC.

In category view I want to show the newest threads.

My code with sorting by thread add date:

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


ForumPost model has foreign key to ForumThread model.

The problem is:
How to sort threads by last post, but if there is no posts then sort by thread add date.

Answer

Use ternary if operator (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);