📅  最后修改于: 2023-12-03 14:59:39.807000             🧑  作者: Mango
In C#, a bool list represents a collection of Boolean values. The List<bool>
class is used to create and manipulate such lists. One common operation is to count the number of true
values in the list. This tutorial will guide you through the process of counting true
values in a List<bool>
object using C#.
List<bool>
List<bool>
and initialize it with desired Boolean values:List<bool> boolList = new List<bool> { true, false, true, false, true };
Count()
method with a lambda expression to count the number of true
values in the list:int trueCount = boolList.Count(b => b == true);
trueCount
variable now contains the count of true
values in the boolList
.Here's a complete example that demonstrates counting true
values in a bool list:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
List<bool> boolList = new List<bool> { true, false, true, false, true };
int trueCount = boolList.Count(b => b == true);
Console.WriteLine($"Number of true values: {trueCount}");
}
}
Output:
Number of true values: 3
In this example, a bool list boolList
is created with 5 Boolean values. The Count()
method is used to count the number of true
values, and the result is printed to the console.
This approach can be used with any List<bool>
object to count the occurrences of true
in the list.
Counting the number of true
values in a List<bool>
using C# is straightforward. By using the Count()
method with a lambda expression, you can easily determine the count of true
occurrences.