【问题标题】:ASP.NET Order bool with not set未设置的 ASP.NET Order bool
【发布时间】:2019-07-02 15:00:25
【问题描述】:

如何先按 null 排序布尔值,然后是 true,然后是 false

return View("Index", db.HolidayRequestForms.ToList().OrderByDescending(e => e.Approved).ThenBy(e => e.RequestID))

我正在为布尔值使用自定义显示模板,我不知道这是否重要

【问题讨论】:

  • not set - 你的意思是Approved 可以为空吗?
  • @Alex 是的,这是一个请求页面,所以可以为空的将被挂起

标签: c# linq boolean


【解决方案1】:

你可以用这个:

myList.OrderBy(v => !v)

【讨论】:

    【解决方案2】:

    您可以使用自定义比较器

    public class ApprovedComparer : IComparer<bool?>
    {
        public int Compare(bool? x, bool? y)
        {
            var a = 0;
            var b = 0;
    
            if (x.HasValue)
                a = x.Value ? 1 : 2;
            if (y.HasValue)
                b = y.Value ? 1 : 2;
    
            return a - b;
        }
    }
    

    用法:

    return View("Index", db.HolidayRequestForms.ToList()
        .OrderBy(e => e.Approved, new ApprovedComparer())
        .ThenBy(e => e.RequestID))
    

    可以在 LinqPad(或普通控制台应用)中测试

    public class Thing
    {
        public string Name { get; set; }
        public bool? Approved { get; set; }
    }
    
    public class ApprovedComparer : IComparer<bool?>
    {
        public int Compare(bool? x, bool? y)
        {
            var a = 0;
            var b = 0;
    
            if (x.HasValue)
                a = x.Value ? 1 : 2;
            if (y.HasValue)
                b = y.Value ? 1 : 2;
    
            return a - b;
        }
    }
    
    void Main()
    {
        var thing1 = new Thing { Approved = null, Name = "Thing 1" };
        var thing2 = new Thing { Approved = true, Name = "Thing 2", };
        var thing3 = new Thing { Approved = false, Name = "Thing 3" };
    
        //note the 'incorrect' order
        var listOfThings = new[] { thing3, thing2, thing1 };
    
        listOfThings
            .OrderBy(x => x.Approved, new ApprovedComparer())
            .Select(x => x.Name) //just for outputting the names
            .Dump(); //LinqPad specifc
    }
    

    输出

    从 .net 4.5 开始,您可以使用 Comparer&lt;T&gt;.Create() 创建一个静态比较器,它可以是“内联”的 - 即,不需要单独的类。

    就我个人而言,我发现单独的课程阅读起来更简洁。不过,这只是我的看法。

    var comparer = Comparer<bool?>.Create((x, y) =>
       {
           var a = 0;
           var b = 0;
    
           if (x.HasValue)
               a = x.Value ? 1 : 2;
           if (y.HasValue)
               b = y.Value ? 1 : 2;
    
           return a - b;
       });
    
    listOfThings
        .OrderBy(x => x.Approved, comparer)
        .Select(x => x.Name) //just for outputting the names
        .Dump(); //LinqPad specifc
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-18
      • 1970-01-01
      • 2012-12-21
      相关资源
      最近更新 更多