比较两组新密钥和缺失密钥

时间:2010-09-19 15:25:27

标签: c# dictionary comparison set

当比较C#中的两个键值字典集时:设置A和设置B,枚举集A中存在但是从集B中丢失的键的最佳方法是什么,反之亦然?

例如:

A = { 1, 2, 5 }
B = { 2, 3, 5 }

比较B与A,缺少键= {1}和新键= {3}。

使用Dictionary<...,...>个对象,可以枚举B中的所有值并使用A.ContainsKey(key);对集合A进行测试,但感觉应该有更好的方法可能涉及有序集合?

4 个答案:

答案 0 :(得分:7)

我知道有两种内置的方法来区别。

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&lt; T&gt;中删除指定集合中的所有元素。对象

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&lt; T&gt; object仅包含该对象或指定集合中存在的元素,但不包含两者。

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"
}

如果你需要更高效的东西,你可能需要推出自己的收藏类型。

答案 1 :(得分:2)

使用SortedDictionary:逻辑为A.Except(A.Intersect(B))

在您确定数据集存在问题之前,请不要担心性能过高。

答案 2 :(得分:0)

您可以使用Except方法。

Dictionary<string, string> dic1 = new Dictionary<string, string>() { { "rabbit", "hat" }, { "frog", "pond" }, { "cat", "house" } };
Dictionary<string, string> dic2 = new Dictionary<string, string>() { { "rabbit", "hat" }, { "dog", "house"}, {"cat", "garden"}};

    var uniqueKeys = dic1.Keys.Except(dic2.Keys);

    foreach (var item in uniqueKeys)
    {
        Console.WriteLine(item);
    }

答案 3 :(得分:0)

所以这里有几个答案可行。但是你最初的问题最好分两部分来解决:

问)当比较C#中的两个键值字典集时:设置A和设置B,枚举集A中存在但是从集B中丢失的键的最佳方法是什么,反之亦然?使用字典&lt; ...,...&gt;对象,可以枚举B中的所有值,并使用A.ContainsKey(key);来测试集合A.,...

如果您从两个词典开始,这可能是最好的方法。要做任何其他事情,需要从两个集合中创建密钥的副本,从而使大多数替代品更加昂贵。

问)...但感觉应该有更好的方法可能涉及一个排序集?

是的,这可以通过排序列表轻松完成。创建两个使用BinarySearch排序的List插入,然后在搜索set 2 ect时遍历set 1。

请参阅此SetList补充和减法操作: http://csharptest.net/browse/src/Library/Collections/SetList.cs#234