Reputation: 657
I'm trying to sort a List<T>
in LINQ on two conditions,
MasterBenefitCode
property value as "QLBEN"
. It should be sorted to the top.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
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
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