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

C#

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

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

スポンサーリンク

方法

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

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

Count()

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

まず、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
 	}
}

Where()メソッド

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

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

using System.Linq;

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

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

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

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

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

まとめ

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

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

コメント

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