How to sort by two properties in Linq

9

I have the following syntax and it is 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 ordering that prevails is OrderByDescending (a => the InitialTime) , leaving no ordering OrderByDescending (a => a.Data) >

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

    
asked by anonymous 27.01.2017 / 19:41

2 answers

12

It happens that whenever OrderBy is executed, it sorts the entire collection , ie the previous sort is disregarded.

Therefore, you must use the 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));
    
27.01.2017 / 19:42
9

Use ThenBy in the second order if you want the default ordering ( 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 the ordering of the start date and 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));
    
27.01.2017 / 19:42