【发布时间】:2022-01-31 17:37:56
【问题描述】:
我有一个 linq 查询,我想按 f.bar 排序,它是一个字符串,但我也想先按 f.foo 排序,它是一个布尔字段。就像下面的查询一样。
(from f in foo
orderby f.foo, f.bar
select f)
虽然这样编译它并没有按预期工作。它只是通过 f.bar 命令忽略布尔字段。
我知道我很愚蠢,但是我需要做什么才能获得这种行为?
谢谢
【问题讨论】:
我有一个 linq 查询,我想按 f.bar 排序,它是一个字符串,但我也想先按 f.foo 排序,它是一个布尔字段。就像下面的查询一样。
(from f in foo
orderby f.foo, f.bar
select f)
虽然这样编译它并没有按预期工作。它只是通过 f.bar 命令忽略布尔字段。
我知道我很愚蠢,但是我需要做什么才能获得这种行为?
谢谢
【问题讨论】:
这应该可以正常工作 - 它应该首先订购具有 false foo 值的实体,然后是具有 true foo 值的实体。
这当然适用于 LINQ to Objects - 您实际使用的是哪个 LINQ 提供程序?
这是一个 LINQ to Objects 示例,确实工作:
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);
}
}
}
【讨论】:
false (0) 按升序(默认)排序在 true (1) 之前。
data.OrderBy(d => d.x).ThenBy(d => d.y)
只是想这样做,它似乎没有隐含的顺序。为了更明确,我做了以下操作:
Something.OrderBy(e=>e.SomeFlag ? 0 : 1)
将某事从真到假排序。
【讨论】:
true 意味着a single bit set to 1,我错了吗?对我来说,true > false 的真相是显而易见的。
true > false 并不广为人知,而 1 > 0 是。
.OrderBy(e => e.SomeFlag == true) 将等效于 .OrderBy(e => e.SomeFlag),而 .OrderBy(e => e.SomeFlag ? 0 : 1) 等效于 .OrderByDescending(e => e.SomeFlag)。前两种在真之前是假,另外两种在假之前是真。
为了更明确地说明所使用的顺序。
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();
【讨论】: