いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

.NET クラスライブラリ探訪-015 (System.Collections.Generic.HashSet) (System.Core, セット, 集合演算)


.net framework 3.5より、コレクションライブラリに以下のクラスが追加されました。

System.Collections.Generic.HashMap


機能的には、pythonとかjavaにあるセットと同じような感じです。
集合演算が行えます。これ、うまく使うととても便利です。


ちなみに、演算子オーバーロードは存在しないので、以下のメソッドを呼ぶことで
集合演算を行います。

処理 対応するメソッド名
結合 UnionWith
減算 ExceptionWith
共通集合 IntersectWith
対称差 SymmetricExceptionWith


集合演算に関しては、SQLで理解した方が分かりやすいです。
以下のページが凄く分かりやすいのでメモメモ。
(なんて言ったってミックさんの記事なので)


以下、サンプルです。

// vim:set ts=4 sw=4 et ws is nowrap ft=cs:
using System;
using System.Collections.Generic;

namespace Demo{

    class HashSetSample{

        static void Main(){

            HashSet<int> setA = new HashSet<int>();
            HashSet<int> setB = new HashSet<int>();

            ClearAndInitializeSet(setA, setB);

            ////////////////////////////////////////
            //
            // 集合演算
            //
            // 結合
            ClearAndInitializeSet(setA, setB);

            setA.UnionWith(setB);
            PrintSet(setA);

            // 減算
            ClearAndInitializeSet(setA, setB);

            setA.ExceptWith(setB);
            PrintSet(setA);

            // 共通集合
            ClearAndInitializeSet(setA, setB);

            setA.IntersectWith(setB);
            PrintSet(setA);

            // 対称差
            ClearAndInitializeSet(setA, setB);

            setA.SymmetricExceptWith(setB);
            PrintSet(setA);

            //
            // 【出力結果】
            // 結合  :123457
            // 減算  :124
            // 共通集合:35
            // 対称差 :1247
            //
        }

        static void ClearAndInitializeSet(HashSet<int> setA, HashSet<int> setB){
            setA.Clear();
            setB.Clear();

            Array.ForEach(new int[]{1,2,3,4,5}, x => setA.Add(x));
            Array.ForEach(new int[]{3,5,7},     x => setB.Add(x));
        }

        static void PrintSet<T>(HashSet<T> set){
            foreach(T element in set){
                Console.Write(element);
            }

            Console.WriteLine();
        }
    }
}


補足:
.NET 4.0以降は、HashSetクラスは、ISetインターフェースを実装するようになっています。


================================
過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。