コレクション

[C#] 2つのコレクションの差集合を取得する(.Except)

2021年8月16日

2つのコレクションの差集合を取得するには、.Exceptを使用します。

※差集合は重複しない要素を取得します。

サンプル

例1)List<int>型の場合

using System.Collections.Generic;
using System.Linq;

//int型のList
List<int> list1 = new List<int>(){1, 2, 3};
List<int> list2 = new List<int>(){3, 4, 5};

//list1とlist2をExceptする
var result = list1.Except(list2).ToList();

結果

{1, 2}

list1を基準として重複していない要素のみ取得するので、1と2が取得されます。

例2)Dictionaryの場合

using System.Collections.Generic;
using System.Linq;

//Dictionary1
Dictionary<string, string> dic1 = new Dictionary<string, string>();
dic1.Add("01", "札幌");
dic1.Add("02", "東京");
dic1.Add("03", "名古屋");

//Dictionary2
Dictionary<string, string> dic2 = new Dictionary<string, string>();
dic2.Add("03", "名古屋");
dic2.Add("04", "大阪");
dic2.Add("05", "福岡");

//dic1とdic2をExceptする
var result2 = dic1.Except(dic2).ToDictionary(x => x.Key, x => x.Value);

結果

["01", "札幌"]
["02", "東京"]

dic1を基準として重複していない要素のみ取得するため、札幌、東京が対象となります。

備考

  • LINQを使用するには、「using System.Linq;」の宣言が必要です。
  • Exceptではコレクション要素で重複しない要素のみ取得します。

関連記事

-コレクション
-, ,