确定.NET中两个IEnumerable <T>集的相对补集

SFu*_*n28 12 .net c# linq vb.net set

有没有一种简单的方法来获得两组的相对补充?也许使用LINQ?

我必须找到A相对于B的相对称赞.A和B都是类型的,HashSet<T>但我认为算法可以更通用(IEnumerable<T>甚至ISet<T>)?

我可以在VB.NET或C#中使用解决方案.

Mar*_*ers 28

你试过Enumerable.Except吗?

setB.Except(setA)
Run Code Online (Sandbox Code Playgroud)

例:

HashSet<int> setB = new HashSet<int> { 1, 2, 3, 4, 5 };
HashSet<int> setA = new HashSet<int> { 1, 3, 5, 7 };
HashSet<int> result = new HashSet<int>(setB.Except(setA));

foreach (int x in result)
    Console.WriteLine(x);
Run Code Online (Sandbox Code Playgroud)

结果:

2
4