Aryan M
Aryan M

Reputation: 657

How to sort a list on a column value

I'm trying to sort a List<T> in LINQ on two conditions,

  1. If the list has the MasterBenefitCode property value as "QLBEN". It should be sorted to the top.
  2. Followed by all the benefits on benefit Name.

I'm trying with the following code,

employerBenefits
  .OrderBy(x => x.MasterBenefitCode == "QLBEN")
  .ThenBy(x => x.Name)
  .ToList();

Please let me know what am I missing here. Is it not possible to add a comparison operator in OrderBy().

Upvotes: 0

Views: 66

Answers (2)

Anu Viswan
Anu Viswan

Reputation: 18155

Another Option to the same (including your comment of secondary MasterBenefitCode),

 var result = employerBenefits
                        .OrderByDescending(x => x.MasterBenefitCode == "QLBEN" ? 3:x.MasterBenefitCode == "QLBEF"?2:1)
                        .ThenBy(x => x.Name)
                        .ToList();

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186678

When comparing Boolean we have false < true (which is quite natural: 0 < 1). So we have to sort in descending order (for true be on the top):

var result = employerBenefits
  .OrderByDescending(x => x.MasterBenefitCode == "QLBEN")
  .ThenBy(x => x.Name)
  .ToList();

Edit: The same with ThenBy which should be turned into .ThenByDescending (see comments below):

 var result = employerBenefits
   .OrderByDescending(x => x.MasterBenefitCode == "QLBEN") 
   .ThenByDescending(x => x.MasterBenefitCode == "QLBEF")
   .ThenBy(x => x.Name) 
   .ToList();

Upvotes: 4

Related Questions