C#比较字典是否相等

时间:2018-09-02 23:18:50

标签: c# dictionary compare

如何最有效地比较两个字典是否相等? -除了密钥的暴力迭代之外,请尝试查找并比较值

var d1 = new Dictionary<string,int>();
d1.Add("a",2);
d1.Add("b",1);
d1.Add("c",1);

var d2 = new Dictionary<string,int>();
d2.Add("c",1);
d2.Add("b",1);
d2.Add("a",2);

如何最有效地比较平等?

不是这样的蛮力:

static bool CompareDictionaries(Dictionary<string,int> d1, Dictionary<string,int> d2)
{
    if (d1.Count != d2.Count) return false;
    foreach(string key in d1.Keys)
    {
        if (!d2.ContainsKey(key)) return false;
        if (d1[key] != d2[key]) return false;
    }
    return true;
}

2 个答案:

答案 0 :(得分:-1)

结合自定义的AbstractSecurityInterceptor扩展名,您可以指定如何将键和值与以下内容进行比较:

SequenceEquals

扩展名:

public static bool Equals<TKey, TValue>(IDictionary<TKey, TValue> a, IDictionary<TKey, TValue> b,
    IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
    if (ReferenceEquals(a, b))
        return true;

    if (b == null || a == null)
        return false;

    if (a.Count != b.Count)
        return false;

    var aOrdered = a.OrderBy(k => k.Key, keyComparer);
    var bOrdered = b.OrderBy(k => k.Key, keyComparer);

    return aOrdered.SequenceEqual(bOrdered, valueComparer);
}

您可以调用OP的特定public static bool SequenceEqual<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> first, IEnumerable<KeyValuePair<TKey, TValue>> second, IEqualityComparer<TValue> valueComparer) { if (valueComparer == null) valueComparer = EqualityComparer<TValue>.Default; if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); using (IEnumerator<KeyValuePair<TKey, TValue>> e1 = first.GetEnumerator()) using (IEnumerator<KeyValuePair<TKey, TValue>> e2 = second.GetEnumerator()) { while (e1.MoveNext()) { if (!(e2.MoveNext() && valueComparer.Equals(e1.Current.Value, e2.Current.Value))) return false; } if (e2.MoveNext()) return false; } return true; } 示例:

Dictionary<string,int>

答案 1 :(得分:-1)

如果Dictionary键相同,则可以使用HashSet进行比较:

var set1 = new HashSet<int>(dictionary1.Values);
var set2 = new HashSet<int>(dictionary2.Values);

然后可以使用“联合”,“相交”,“ HashSet暴露”。另外,您可以使用以下方法:

bool isEqual = set1.SetEquals(set2);

根据您的情况,基准测试是(HashSet vs Dictionary)here