Linq 按布尔值排序 [英] Linq order by boolean

查看:33
本文介绍了Linq 按布尔值排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 linq 查询,我想按 f.bar(一个字符串)排序,但我也想先按 f.foo(一个布尔字段)排序.喜欢下面的查询.

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)

尽管这可以编译,但它并没有按预期工作.它只是通过 f.bar 进行排序,忽略布尔字段.

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?

谢谢

推荐答案

这应该可以正常工作 - 它应该首先对具有 false foo 值的实体进行排序,然后是那些具有 true foo 值.

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

这当然适用于 LINQ to Objects - 您实际使用的是哪个 LINQ 提供程序?

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

这是一个确实有效的 LINQ to Objects 示例:

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

}

这篇关于Linq 按布尔值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆