[C#][Linq]Count()でリスト(List)の要素の個数を検索するには?

C#

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

System.LinqのCount()を使って、リスト(List)の要素の個数を検索する方法を紹介します。

スポンサーリンク

方法

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

System.LinqのCount()を使って、リスト(List)の要素の個数を検索するには、ラムダ式を使います。

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

using System.Linq;

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

Count()メソッドの引数にラムダ式を指定し、ラムダ式で「引数 == 要素」のような条件式を返します。

list.Count(item => item == 要素);

上記のCount()は、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, 1, 1, 2};
		
		int count1 = numbers.Count(item => item == 1);
		int count2 = numbers.Count(item => item == 2);
		
		Console.WriteLine(count1); //3
		Console.WriteLine(count2); //2
 	}
}

コメント

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