计算 bool 属性 为真的实例数 - C#

Counting for how many instances a bool property is true - C#

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

为了演示它,我创建了一个带有布尔值 属性 'InnerProperty' 的 class '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;
    }
}

您可以使用接受谓词 ("a function to test each element for a condition.") 的 LINQ Count:

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

您可以像下面那样使用 Linq System.Linq。此外,InnerProperty 应该是一个字段而不是 属性,因为对于 private 属性 setter 没有多大意义

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

您可以通过更简单的方式完成此操作:

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

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

只需使用 Lambda Expression.

与其他答案基本相同,使用表达式 bodied member :

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