Max A Max A - 3 months ago 17
ASP.NET (C#) Question

Orderby ASC/DESC when certain state

I want to filter on certain elements in my table, but when there is a certain state in the table I want to filte the same in decending.

Example:


When the state is "Open" I want to filter on "tijdSluit" ascending. When te state is "Gesloten" I want to filter on "tijdSluit" descending.


The code I use now:

return View(db.GetAllRequests().OrderBy(Request => Request.request.Status).ThenBy(Request => Request.request.tijdSluit));


The problem is that you can't filter on ascending and descending in the same table. How can I fix this?

I tried this:

return View(db.GetAllRequests().Where(Request => Request.request.Status == 1).OrderBy(Request => Request.request.Status).Where(Request => Request.request.Status != 1).OrderByDescending(Request => Request.request.tijdSluit));


But when I run that code I get a empty table.

How can I do this correct?

Answer

Ofcourse, it isn't possible to order you table asc and desc at the same time. Maybe in your case you need two ordered sequences? Somwthing like this?

var allRequests = db.GetAllRequests();
var openRequests = allRequests.Where(Request => Request.request.Status == 1).OrderBy(Request => Request.request.Status).ToList();
var otherRequests = allRequests.Where(Request => Request.request.Status != 1).OrderByDescending(Request => Request.request.tijdSluit)).ToList();
openRequests.AddRange(otherRequests);
return View(openRequests);