Home > OS >  OrderByDescending - specific data 1st and then rest in order
OrderByDescending - specific data 1st and then rest in order

Time:12-06

We have data as follows

Created On Supplier
01-Nov-21 ABC
02-Nov-21 XYZ
15-Nov-21 ABC
20-Nov-21 MNO
25-Nov-21 ABC

So we want to record in descending order of creation but 1st want all "ABC" records on the top.

I tried with this one, but didn't worked.

object.OrderByDescending(m => m.name== "ABC").ThenBy(x => x.CreatedOn)

So instead of getting records as follows

01-Nov-21   |   ABC  
15-Nov-21   |   ABC
25-Nov-21   |   ABC  
02-Nov-21   |   XYZ  
20-Nov-21   |   MNO 

It was coming in same order as above i.e. based on createdOn field

Am i missing anything here?

CodePudding user response:

in descending order of creation but 1st want all "ABC" records on the top

You need to use ThenByDescending - using OrderByDescending initially doesn't then set the sorting of the date up to be descending too

I don't personally think you should sort a bool in your first clause, because it's not obvious to everyone how booleans sort. Rather than it be something one has to remember/look up, I would recommend that you use the bool to generate an int for sorting because everyone can easily understand your intent (everyone can put 0 and 1 into ascending order):

foreach(var x in list.OrderBy(m => m.name == "ABC" ? 0 : 1).ThenByDescending(x => x.CreatedOn))
  //process your objects in turn here

To achieve a "date descending but all ABC on top" you first sort on whether something is ABC or not (and bear in mind that that's an exact, case sensitive match, unless this query is being translated to SQL and send to a DB like SQL server, where case sensitivity depends on the collation of the column being sorted/where trailing spaces may be ignored), then you want to sort the date descending with ThenByDescending.

  • Related