どうも、ちょげ(@chogetarou)です。
配列(Array)の要素の個数を検索する方法を紹介します。
方法

配列(Array)の要素の個数を検索するには、System.LinqのCount()を使います。
まず、System.Linqを導入します。
using System.Linq;
そして、配列(Array)からCount()メソッドを呼び出します。
Count()メソッドの引数にラムダ式を指定し、ラムダ式で「引数 == 要素」を返します。
array.Count(item => item == 要素);
上記のConunt()は、指定した要素を検索して、要素の個数を返します。
使用例
using System;
using System.Linq;
public class Example
{
public static void Main()
{
int[] numbers = new int[8] {4, 3, 5, 1, 2, 3, 4, 3};
int count1 = numbers.Count(item => item == 3);
int count2 = numbers.Count(item => item == 4);
Console.WriteLine(count1); //3
Console.WriteLine(count2); //2
}
}
コメント