Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq order by boolean

Tags:

c#

linq

That should work fine - it should order the entities with a false foo value first, then those with a true foo value.

That certainly works in LINQ to Objects - which LINQ provider are you actually using?

Here's a LINQ to Objects example which does work:

using System;
using System.Linq;

public static class Test
{
    public static void Main()
    {
        var data = new[]
        {
            new { x = false, y = "hello" },
            new { x = true, y = "abc" },
            new { x = false, y = "def" },
            new { x = true, y = "world" }
        };

        var query = from d in data
                    orderby d.x, d.y
                    select d;

        foreach (var result in query)
        {
            Console.WriteLine(result);
        }
    }

}

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.


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; 
    }
}