开发者

Linq order by boolean

开发者 https://www.devze.com 2023-02-19 11:15 出处:网络
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, f开发者_如何学运维irst. Like the query below.

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, f开发者_如何学运维irst. 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


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


Please try following code if you get list orderby true .

db.member.where(x=>x.id==memberId).OrderBy(x=>!x.IsPrimary?1:0).ToList();
0

精彩评论

暂无评论...
验证码 换一张
取 消