简体   繁体   English

有人可以向我解释一下这段代码是如何工作的吗?

[英]Can someone explain to me how this code works please?

The point of this code is to create a function which returns the number of true values in an array.这段代码的重点是创建一个 function,它返回数组中真值的数量。 So if someone were to input an array that's [true, false, true, false] the ouput would be 2. I didn't create this code, this is one of the code solutions for this practice problem on a site called edabit.因此,如果有人要输入一个[true, false, true, false]的数组,则输出将为 2。我没有创建此代码,这是在一个名为 edabit 的网站上解决此练习问题的代码解决方案之一。 I'm new to coding, can someone explain how inputting val => val into arr.Count() returns only the number of true values?我是编码新手,有人可以解释如何将val => val输入arr.Count()只返回真值的数量吗? Thanks.谢谢。

using System.Linq;

public class Program {
    public static int CountTrue(bool[] arr) {
        return arr.Count(val => val);
    }
}

Probably you would understand it better if written like this如果这样写,你可能会更好地理解它

arr.Count(val => val == true);

Predicate val is equivalent to val == true谓词val等价于val == true

This Count overload takes as parameter a function to test each element for a condition.Count重载将 function 作为参数来测试每个元素的条件。 It will filter those where condition returns true and count them.它将过滤条件返回true的那些并计算它们。

Count iterates through each item and increments the Count if the expression is true. Count遍历每个项目并在表达式为真时增加 Count。 To expand what it's doing:扩展它正在做的事情:

public static int CountTrue(bool[] arr)
{
    return arr.Count(val => val == true);
}

To count the number of false values, you would do the following:要计算错误值的数量,您可以执行以下操作:

public static int CountFalse(bool[] arr)
{
    return arr.Count(val => val == false);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM