C#のリストで重複を検索する
この投稿では、C#のリストで重複を見つける方法について説明します。
1.使用する Enumerable.GroupBy()
方法
使用できます Enumerable.GroupBy() 値に基づいて要素をグループ化し、1回だけ表示されるグループを除外して、重複キーを残します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { List<int> list = new List<int>() {3, 5, 3, 2, 7, 7, 5, 6}; IEnumerable<int> duplicates = list.GroupBy(x => x) .Where(g => g.Count() > 1) .Select(x => x.Key); Console.WriteLine("Duplicate elements are: " + String.Join(",", duplicates)); } } /* 出力: Duplicate elements are: 3,5,7 */ |
上記のコードは、 SelectMany() 方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { List<int> list = new List<int>() {3, 5, 3, 2, 7, 7, 5, 6}; IEnumerable<int> duplicates = list.GroupBy(x => x) .SelectMany(g => g.Skip(1)); Console.WriteLine("Duplicate elements are: " + String.Join(",", duplicates)); } } /* 出力: Duplicate elements are: 3,5,7 */ |
メソッド構文よりもLINQのクエリ構文を使用する場合は、次の例に示すように、クエリ式を作成します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { List<int> list = new List<int>() {3, 5, 3, 2, 7, 7, 5, 6}; IEnumerable<int> duplicates = from x in list group x by x into g where g.Count() > 1 select g.Key; Console.WriteLine("Duplicate elements are: " + String.Join(",", duplicates)); } } /* 出力: Duplicate elements are: 3,5,7 */ |
リスト内の重複要素の頻度をカウントする辞書を作成することもできます。次のコード例は、頻度マップを実装する方法を示しています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { List<int> list = new List<int>() {3, 5, 3, 2, 7, 7, 5, 6}; Dictionary<int, int> freqMap = list.GroupBy(x => x) .Where(g => g.Count() > 1) .ToDictionary(x => x.Key, x => x.Count()); Console.WriteLine("[Value, Count]: " + String.Join(",", freqMap)); } } /* 出力: [Value, Count]: [3, 2],[5, 2],[7, 2] */ |
2.使用する HashSet
最後に、 HashSet<T>
、以下に示すように:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { List<int> list = new List<int>() {3, 5, 3, 2, 7, 7, 5, 6}; HashSet<int> hashset = new HashSet<int>(); IEnumerable<int> duplicates = list.Where(e => !hashset.Add(e)); Console.WriteLine("Duplicate elements are: " + String.Join(",", duplicates)); } } /* 出力: Duplicate elements are: 3,7,5 */ |
これで、C#のリストで重複を見つけることができます。