How to sort by two properties in Linq

Asked

Viewed 487 times

10

I have the following syntax and it’s not working

return View(trabalhos.Where(a => a.Usuario == User.Identity.Name && 
                                 a.Data.Month == DateTime.Today.Month && 
                                 a.Data.Year == DateTime.Today.Year).ToList()
                                .OrderByDescending(a => a.Data)
                                .OrderByDescending(a => a.HoraInicial));

Notice that I have two attributes with ordering Orderbydescending.

In this example the prevailing ordination is Orderbydescending(a => a.Initial), leaving without effect any ordination Orderbydescending(a => a.Data)

I would like the two fields to sort first by Date and after the sort date do the Start Time.

  • Did you have your question answered? Something needs to be improved?

2 answers

12

It happens that whenever OrderBy is executed, he orders the entire collection, that is, the previous ordination is disregarded.

So we need to use the method ThenByDescending()

trabalhos.Where(a => a.Usuario == User.Identity.Name && 
                     a.Data.Month == DateTime.Today.Month && 
                     a.Data.Year == DateTime.Today.Year).ToList()
                     .OrderByDescending(a => a.Data).ThenByDescending(a => a.HoraInicial));

10

Utilize ThenBy in the second sort if you want the default sort (ASC)

return View(trabalhos.Where(
a => a.Usuario == User.Identity.Name && 
a.Data.Month == DateTime.Today.Month && 
a.Data.Year == DateTime.Today.Year).ToList()
.OrderByDescending(a => a.Data).ThenBy(a => a.HoraInicial));

Or use ThenByDescending in the second order if you want to order the date and initial time decreasing (DESC)

return View(trabalhos.Where(
a => a.Usuario == User.Identity.Name && 
a.Data.Month == DateTime.Today.Month && 
a.Data.Year == DateTime.Today.Year).ToList()
.OrderByDescending(a => a.Data).ThenByDescending(a => a.HoraInicial));
  • 1

    30 seconds in front of me :p +1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.