Caution

お使いのブラウザはJavaScriptが実行できない状態になっております。
当サイトはWebプログラミングの情報サイトの為、
JavaScriptが実行できない環境では正しいコンテンツが提供出来ません。
JavaScriptが実行可能な状態でご閲覧頂くようお願い申し上げます。

C#辞典

HashSet<T>

重複を自動で排除するコレクション『HashSet<T>』です。集合演算(和集合・積集合・差集合)が得意で、大量データの重複チェックも高速に行えます。

構文
// HashSet を作成します。
HashSet<T> セット = new HashSet<T>();

// 既存コレクションから作成します(重複は自動除去)。
HashSet<T> セット = new HashSet<T>(コレクション);
メソッド一覧
メソッド / プロパティ概要
Add(item)要素を追加します。既に存在する場合は追加されず false を返します。
Remove(item)指定した要素を削除します。成功すると true を返します。
Contains(item)要素が存在するかを bool で返します。List より高速です。
Count要素数を返します。
UnionWith(other)他のコレクションとの和集合(どちらかに含まれる要素)に変更します。
IntersectWith(other)他のコレクションとの積集合(両方に含まれる要素のみ)に変更します。
ExceptWith(other)other に含まれる要素を除いた差集合に変更します。
IsSubsetOf(other)自身が other の部分集合かどうかを返します。
サンプルコード
using System;
using System.Collections.Generic;

// 重複が自動で排除されます。
HashSet<int> セット = new HashSet<int> { 1, 2, 3, 2, 1 };
Console.WriteLine(セット.Count); // 3(重複が除かれます)

// 既存リストから重複を取り除きます。
List<string> タグリスト = new List<string> { "C#", "C++", "C#", "Python", "C++" };
HashSet<string> ユニークタグ = new HashSet<string>(タグリスト);
foreach (string タグ in ユニークタグ) {
	Console.Write(タグ + " "); // C# C++ Python (順序は保証されません)
}
Console.WriteLine();

// 和集合(UnionWith): どちらかに含まれる要素。
HashSet<int> A = new HashSet<int> { 1, 2, 3, 4 };
HashSet<int> B = new HashSet<int> { 3, 4, 5, 6 };
A.UnionWith(B);
Console.WriteLine(string.Join(", ", A)); // 1, 2, 3, 4, 5, 6

// 積集合(IntersectWith): 両方に含まれる要素のみ。
HashSet<int> C = new HashSet<int> { 1, 2, 3, 4 };
HashSet<int> D = new HashSet<int> { 3, 4, 5, 6 };
C.IntersectWith(D);
Console.WriteLine(string.Join(", ", C)); // 3, 4

// 差集合(ExceptWith): C には含まれ D には含まれない要素。
HashSet<int> E = new HashSet<int> { 1, 2, 3, 4 };
HashSet<int> F = new HashSet<int> { 3, 4, 5, 6 };
E.ExceptWith(F);
Console.WriteLine(string.Join(", ", E)); // 1, 2
概要

『HashSet<T>』は要素の順序を保証しませんが、『Contains()』による検索が非常に高速です。大量のデータから重複を取り除く処理や、「既に処理済みかどうか」の高速チェックに特に有効です。

『UnionWith()』『IntersectWith()』『ExceptWith()』は呼び出したインスタンス自身を変更します。元のセットを保持したい場合は事前にコピーを作成してください。

順序付きコレクションには『IEnumerable<T> / IList<T>』を参照してください。

記事の間違いや著作権の侵害等ございましたらお手数ですがまでご連絡頂ければ幸いです。