按布尔排序

我得到了一个 linq 查询,我想按 f.bar 排序,它是一个字符串,但我也想按 f.foo 排序,它首先是一个布尔字段。像下面的查询。

(from f in foo
orderby f.foo, f.bar
select f)

虽然这个编译并不像预期的那样工作,它只是按 f.bar 排序,忽略了布尔字段。

我知道我很傻,但是我要怎么做才能做出这种行为呢?

谢谢

111969 次浏览

这应该可以很好地工作-它应该排序的实体与 首先是 false foo 值,然后那些与 true的 foo 值。

这在 LINQtoObjects 中当然可行——您实际上使用的是哪个 LINQ 提供程序?

下面是 是的工作的 LINQtoObjects 示例:

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

}

只是想这样做,它似乎没有隐含的命令。我这样做是为了更加明确:

Something.OrderBy(e=>e.SomeFlag ? 0 : 1)

对真假进行分类。

为了更明确地说明所使用的顺序。

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

如果您得到 list orderby true,请尝试下面的代码。

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