Comparing 2 Dictionary Instances

后端 未结 4 1817
忘掉有多难
忘掉有多难 2020-12-03 09:33

I want to compare the contents of two Dictionary instances regardless of the order of the items they contain. SequenceEquals

4条回答
  •  情深已故
    2020-12-03 10:12

    var contentsEqual = source.DictionaryEqual(target);
    
    // ...
    
    public static bool DictionaryEqual(
        this IDictionary first, IDictionary second)
    {
        return first.DictionaryEqual(second, null);
    }
    
    public static bool DictionaryEqual(
        this IDictionary first, IDictionary second,
        IEqualityComparer valueComparer)
    {
        if (first == second) return true;
        if ((first == null) || (second == null)) return false;
        if (first.Count != second.Count) return false;
    
        valueComparer = valueComparer ?? EqualityComparer.Default;
    
        foreach (var kvp in first)
        {
            TValue secondValue;
            if (!second.TryGetValue(kvp.Key, out secondValue)) return false;
            if (!valueComparer.Equals(kvp.Value, secondValue)) return false;
        }
        return true;
    }
    

提交回复
热议问题