Pet*_*ron 5 c# comparison dictionary set
当比较C#中的两个键值字典集:集合A和集合B时,枚举集合A中存在但是从集合B中丢失的密钥的最佳方法是什么,反之亦然?
A = { 1, 2, 5 }
B = { 2, 3, 5 }
Run Code Online (Sandbox Code Playgroud)
比较B与A,缺少键= {1}和新键= {3}.
使用Dictionary<...,...>对象,可以枚举B中的所有值并使用集合A进行测试A.ContainsKey(key);,但感觉应该有更好的方法可能涉及有序集合?
我知道有两种内置方式可以做出设置差异.
通过使用默认的相等比较器来比较值,生成两个序列的集合差异.
例:
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"
}
Run Code Online (Sandbox Code Playgroud)
从当前HashSet <T>对象中删除指定集合中的所有元素.
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"
}
Run Code Online (Sandbox Code Playgroud)
2b)HashSet <T> .SymmetricExceptWith
修改当前HashSet <T>对象以仅包含该对象或指定集合中存在的元素,但不包含两者.
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"
}
Run Code Online (Sandbox Code Playgroud)
如果您需要更高性能的东西,您可能需要滚动自己的集合类型.