[C#]リスト(List)の条件を満たす要素の個数を検索するには?

C#

どうも、ちょげ(@chogetarou)です。

List(リスト)の条件を満たす要素の個数を検索する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

List(リスト)の条件を満たす要素の個数を検索する方法は、2つあります。

Count()

1つは、System.LinqのCount()メソッドを使う方法です。

まず、System.Linqを導入します。

using System.Linq;

そして、リスト(List)からCount()メソッドを呼び出します。

Count()メソッドの引数にラムダ式を指定し、ラムダ式で引数を比較する条件式を返します。

list.Count(item => 条件式);

上記のCount()は、Count()を呼び出したリスト内を検索して、条件式でTrueとなる要素の個数を返します。

Count()の引数のラムダ式は、引数でリストの要素を取得します。

使用例

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
 	}
}

Where()メソッド

もう1つは、Where()メソッドを使う方法です。

まず、System.Linqを導入します。

using System.Linq;

次に、リスト(List)からWhere()メソッドを呼び出します。

Where()メソッドの引数にラムダ式を指定し、引数を比較するラムダ式で条件式を返します。

そして、Where()メソッドからCount()メソッドを呼び出します。

list.Where(item => 条件式).Count();

上記のWhere().Count()は、Where()を呼び出したリスト内を検索して、条件式でTrueとなる要素の個数を返します。

Where()の引数のラムダ式は、引数でリストの要素を取得します。

使用例

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.Where(item => item < 3).Count();
		int count2 = numbers.Where(item => item % 2 != 0).Count();
		
		Console.WriteLine(count1); //2
		Console.WriteLine(count2); //5
 	}
}

まとめ

List(リスト)の条件を満たす要素の個数を検索する方法は、次の2つです。

  • Count()メソッドを使う方法
  • Where()メソッドを使う方法

コメント

タイトルとURLをコピーしました