'Linq order by boolean
I've got a linq query that I want to order by f.bar, which is a string, but I also want to order it by f.foo, which is a boolean field, first. Like the query below.
(from f in foo
orderby f.foo, f.bar
select f)
Although this compiles it doesn't work as expected. It just orders by f.bar ignoring the boolean field.
I'm being daft I know, but what do I need to do to get this behaviour?
Thanks
Solution 1:[1]
Just wanted to do this and it seems like something with no implicit ordering. I did the following to be more explicit:
Something.OrderBy(e=>e.SomeFlag ? 0 : 1)
to sort something true to false.
Solution 2:[2]
In order to be more explicit about the order being used.
Something.OrderBy(e => e.SomeFlag, new BooleanComparer());
public class BooleanComparer : IComparer<bool>
{
public int Compare(bool x, bool y)
{
int p = x ? 1 : 0;
int q = y ? 1 : 0;
return p - q;
}
}
Solution 3:[3]
Please try following code if you get list orderby true .
db.member.where(x=>x.id==memberId).OrderBy(x=>!x.IsPrimary?1:0).ToList();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | JonnyRaa |
Solution 2 | |
Solution 3 |