どうも、ちょげ(@chogetarou)です。
System.LinqのCount()を使って、リスト(List)の条件を満たす要素の個数を検索する方法を紹介します。
方法

System.LinqのCount()を使って、リスト(List)の条件を満たす要素の個数を検索するには、ラムダ式を使います。
まず、System.Linqを導入します。
using System.Linq;
そして、リスト(List)からCount()メソッドを呼び出します。
Count()メソッドの引数にラムダ式を指定し、ラムダ式で引数を比較する条件式を返します。
list.Count(item => 条件式);
上記のCount()は、Count()を呼び出したリスト内を検索して、条件式でTrueとなる要素の個数を返します。
使用例
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
List<int> numbers = new List<int>() {1, 2, 3, 4, 5, 6, 7, 8, 9};
int count1 = numbers.Count(item => item > 6);
int count2 = numbers.Count(item => item % 2 == 0);
Console.WriteLine(count1); //3
Console.WriteLine(count2); //4
}
}
コメント