LINQの拡張メソッドを使うことでも、HashSet・SortedSetと同様の集合演算を行うことができます。 それぞれ対応するメソッドは次のとおりです。
演算 | HashSet/SortedSetのメソッド | LINQの拡張メソッド |
---|---|---|
積集合 | IntersectWith | Intersect |
和集合 | UnionWith | Union |
差集合 | ExceptWith | Except |
対象差 | SymmetricExceptWith | - |
以下の例はこれらのメソッドを使ってHashSet・SortedSetと同様の集合演算を行う例です。 LINQでは、SymmetricExceptWithに相当するような対象差を求めるメソッドは直接提供されませんが、以下の例のように差集合同士の和集合を求めることで対象差を求めることができます。
LINQの拡張メソッドを使って配列同士の積集合・和集合・差集合・対象差を求める
using System;
using System.Collections.Generic;
using System.Linq;
class Sample {
static void Main()
{
var set1 = new int[] {6, 2, 0, 4, 8};
var set2 = new int[] {3, 1, 2, 0, 4};
// 積集合を求める
Console.WriteLine(string.Join(", ", set1.Intersect(set2)));
// 和集合を求める
Console.WriteLine(string.Join(", ", set1.Union(set2)));
// 差集合を求める
Console.WriteLine(string.Join(", ", set1.Except(set2)));
// 対象差を求める
var diffset1 = set1.Except(set2);
var diffset2 = set2.Except(set1);
Console.WriteLine(string.Join(", ", diffset1.Union(diffset2)));
}
}
実行結果
2, 0, 4, 6, 2, 0, 4, 8, 3, 1, 6, 8, 6, 8, 3, 1,