简体   繁体   中英

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. 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. I'm new to coding, can someone explain how inputting val => val into arr.Count() returns only the number of true values? 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

This Count overload takes as parameter a function to test each element for a condition. It will filter those where condition returns true and count them.

Count iterates through each item and increments the Count if the expression is true. 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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