【问题标题】:Counting for how many instances a bool property is true - C# [duplicate]计算布尔属性为真的实例数 - C# [重复]
【发布时间】:2018-08-08 12:17:23
【问题描述】:

我有一个具有 bool 属性的某个对象的 IEnumerable。我想以紧凑(就代码行而言)和可读的方式计算该属性设置为 true 的对象数量。

为了演示它,我创建了一个具有布尔属性“InnerProperty”的类“Obj”。静态函数“CountInner”实现了上面定义的逻辑。我怎样才能更紧凑地实现它?

public class Obj
{
    private bool InnerProperty { get; set; } = false;

    public static int CountInner(IEnumerable<Obj> list)
    {
        var count = 0;
        foreach (var l in list)
        {
            if (l.InnerProperty)
            {
                count++;
            }
        }
        return count;
    }
}

【问题讨论】:

    标签: c# linq ienumerable


    【解决方案1】:

    您可以使用 LINQ 的 Count 接受谓词(“测试每个元素的条件的函数。”):

    public static int CountInner(IEnumerable<Obj> list)
    {
        return list.Count(x => x.InnerProperty);
    }
    

    【讨论】:

      【解决方案2】:

      与其他答案基本相同,使用表达式主体成员:

      public static int CountInner(IEnumerable<Obj> list) => list.Count(x => x.InnerProperty);
      

      【讨论】:

        【解决方案3】:

        您可能可以使用 Linq System.Linq,如下所示。此外,InnerProperty 应该是一个字段而不是一个属性,因为对于 private 属性设置器来说没有多大意义

        public static int CountInner(IEnumerable<Obj> list)
        {
            var count = list.Where(l => l.InnerProperty).Count(); 
            return count;
        }
        

        【讨论】:

          【解决方案4】:

          你可以用更简单的方法来做:

          public class Obj
          {
              private bool InnerProperty { get; set; } = false;
          
              public static int CountInner(IEnumerable<Obj> list)
              {
                  return list.Count(b => b.InnerProperty);
              }
          }
          

          只需使用Lambda Expression

          【讨论】:

            猜你喜欢
            • 2021-07-18
            • 1970-01-01
            • 1970-01-01
            • 2023-04-02
            • 2017-01-02
            • 2020-10-17
            • 1970-01-01
            • 1970-01-01
            • 2013-07-10
            相关资源
            最近更新 更多