C# LINQ Orderby - How does true/false affect orderby?
The OrderBy method will sort items in ascending order by default. Now, given that the numeric representation of a boolean is:
false
= 0true
= 1
false
values will naturally come first. If you want to reverse the order just use the descending
keyword:
var trueData = (from data in x
orderby numbersToFilterBy.Contains(data.Id) descending, data.Id
select data).ToList();
Basically, false
is earlier than true
... think of them as false=0, true=1. This is in-keeping with the documentation for bool.CompareTo(bool)
.
If you want to prioritize "true" values to the start, just use OrderByDescending
instead.
Ordering isn't about priority – it's about ordinal value. You're doing an ascending order against a boolean value, and false
has a lower ordinal value than true
in that context.