どうも、ちょげ(@chogetarou)です。
配列(Array)から重複がある要素とその個数を抽出する方法を紹介します。
方法

配列(Array)から重複がある要素とその個数を抽出するには、System.Linqを使います。
まず、System.Linqを導入します。
using System.Linq;
次に、配列(array)からGroupBy()を呼び出します。
GroupBy()の引数に、引数をそのまま返すラムダ式を指定します。
GroupBy()からWhere()を呼び出し、Where()のラムダ式で「引数.Count() > 1」を返します。
そして、Where()からToDictionary()を呼び出します。
ToDictionary()の第1引数に引数のKeyプロパティを返すラムダ式、第2引数に引数のCount()を返すラムダ式を指定します。
var duplicates = array.GroupBy(x => x)
.Where(x => x.Count() > 1)
.ToDictionary(x => x.Key, y => y.Count());
上記のToDictionary()は、重複する要素とその個数を抽出した辞書を返します。
使用例
using System;
using System.Linq;
public class Example
{
public static void Main()
{
int[] numbers = new int[] { 1, 2, 3, 1, 1, 4, 3, 5 };
var duplicates = numbers.GroupBy(x => x)
.Where(x => x.Count() > 1)
.ToDictionary(x => x.Key, y => y.Count());
Console.WriteLine(String.Join(", ", duplicates)); //[1, 3], [3, 2]
}
}
コメント