Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ OrderBy / ThenBy with conditional sorting

I am trying to sort a list by date and then by description name, however I need all elements with a certain description to be the top element for each date.

Example:

01-02-2014 "Description A"
01-02-2014 "Description B"
01-02-2014 "Description C"
01-02-2014 "Description D"
01-02-2014 "Description E"

02-02-2014 "Description A"
02-02-2014 "Description B"
02-02-2014 "Description C"
02-02-2014 "Description D"
02-02-2014 "Description E"

How I need it sorted is by date and description but also all Description B elements at top of list within each date. Like this,

01-02-2014 "Description B" <-- Top (Rest below is still sorted ascending)
01-02-2014 "Description A"
01-02-2014 "Description C"
01-02-2014 "Description D"
01-02-2014 "Description E"

02-02-2014 "Description B" <-- Top (Rest below is still sorted ascending)
02-02-2014 "Description A"
02-02-2014 "Description C"
02-02-2014 "Description D"
02-02-2014 "Description E"

I've tried doing this with LINQ but I am not sure if it can be done as a single query.

return ListOfItems.OrderByDescending(x => x.Date).ThenBy(x => x.Type)
like image 214
devfunkd Avatar asked Jan 27 '26 18:01

devfunkd


1 Answers

This series of ordering statements will sort it how your example shows

return ListOfItems.OrderBy(x => x.Date)
                  .ThenByDescending(x => x.Type == "Description B")
                  .ThenBy(x => x.Type);
like image 138
Tim S. Avatar answered Jan 29 '26 08:01

Tim S.