我想比较 2 个哈希集并找出差异
I want to compare 2 hash sets and take out the differences
我有 2 个这样的哈希集。
Hash_1 = {1, 2, 3, 4, 5}
Hash_2 = {4, 5, 6, 7, 8}
我正在使用 C#
我想比较这两组,并希望得到类似
的输出
Hash_3 = {1, 2, 3, 6, 7, 8}
你要的是:Hash_1不带Hash_2,Hash_2不带Hash_1,然后合并为一组。
所以让我们从没有 Hash_2 的 Hash_1 开始:
var modified1 = Hash_1.Except(Hash_2);
然后 Hash_2 没有 Hash_1:
var modified2 = Hash_2.Except(Hash_1);
现在让我们把它们结合起来:
var result = modified1.Concat(modified2);
或者简而言之:
var result = Hash_1.Except(Hash_2).Concat(Hash_2.Except(Hash_1));
或者您可以使用 SymmetricExceptWith
Modifies the current HashSet<T>
object to contain only elements that
are present either in that object or in the specified collection, but
not both.
var h1 = new HashSet<int>() { 1, 2, 3, 4, 5 };
var h2 = new HashSet<int>() { 4, 5, 6, 7, 8 };
h1.SymmetricExceptWith(h2);
Console.WriteLine(string.Join(",", h1));
输出
1,2,3,7,6,8
内部仅使用
foreach (T item in other)
{
if (!Remove(item))
{
AddIfNotPresent(item);
}
}
我有 2 个这样的哈希集。
Hash_1 = {1, 2, 3, 4, 5}
Hash_2 = {4, 5, 6, 7, 8}
我正在使用 C#
我想比较这两组,并希望得到类似
的输出Hash_3 = {1, 2, 3, 6, 7, 8}
你要的是:Hash_1不带Hash_2,Hash_2不带Hash_1,然后合并为一组。
所以让我们从没有 Hash_2 的 Hash_1 开始:
var modified1 = Hash_1.Except(Hash_2);
然后 Hash_2 没有 Hash_1:
var modified2 = Hash_2.Except(Hash_1);
现在让我们把它们结合起来:
var result = modified1.Concat(modified2);
或者简而言之:
var result = Hash_1.Except(Hash_2).Concat(Hash_2.Except(Hash_1));
或者您可以使用 SymmetricExceptWith
Modifies the current
HashSet<T>
object to contain only elements that are present either in that object or in the specified collection, but not both.
var h1 = new HashSet<int>() { 1, 2, 3, 4, 5 };
var h2 = new HashSet<int>() { 4, 5, 6, 7, 8 };
h1.SymmetricExceptWith(h2);
Console.WriteLine(string.Join(",", h1));
输出
1,2,3,7,6,8
内部仅使用
foreach (T item in other)
{
if (!Remove(item))
{
AddIfNotPresent(item);
}
}