【发布时间】:2010-06-02 18:59:59
【问题描述】:
有没有简单的方法来获得两组的relative complement?也许使用 LINQ?
我必须找到集合 A 相对于 B 的相对互补。A 和 B 都是 HashSet<T> 类型,但我认为算法可以更通用(IEnumerable<T> 甚至 ISet<T>)?
我可以在 VB.NET 或 C# 中使用解决方案。
【问题讨论】:
有没有简单的方法来获得两组的relative complement?也许使用 LINQ?
我必须找到集合 A 相对于 B 的相对互补。A 和 B 都是 HashSet<T> 类型,但我认为算法可以更通用(IEnumerable<T> 甚至 ISet<T>)?
我可以在 VB.NET 或 C# 中使用解决方案。
【问题讨论】:
你试过Enumerable.Except吗?
setB.Except(setA)
例子:
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);
结果:
2 4【讨论】: