我知道两种用于设置差异的内置方法。
1) Enumerable.Except
通过使用默认相等比较器比较值来产生两个序列的集合差。
例子:
IEnumerable<int> a = new int[] { 1, 2, 5 };
IEnumerable<int> b = new int[] { 2, 3, 5 };
foreach (int x in a.Except(b))
{
Console.WriteLine(x); // prints "1"
}
2a) HashSet<T>.ExceptWith
从当前 HashSet 对象中移除指定集合中的所有元素。
HashSet<int> a = new HashSet<int> { 1, 2, 5 };
HashSet<int> b = new HashSet<int> { 2, 3, 5 };
a.ExceptWith(b);
foreach (int x in a)
{
Console.WriteLine(x); // prints "1"
}
2b)HashSet<T>.SymmetricExceptWith
修改当前的 HashSet 对象以仅包含存在于该对象或指定集合中的元素,但不能同时包含两者。
HashSet<int> a = new HashSet<int> { 1, 2, 5 };
HashSet<int> b = new HashSet<int> { 2, 3, 5 };
a.SymmetricExceptWith(b);
foreach (int x in a)
{
Console.WriteLine(x); // prints "1" and "3"
}
如果您需要更高性能的东西,您可能需要推出自己的集合类型。