Comparing 2 Dictionary Instances

后端 未结 4 1836
忘掉有多难
忘掉有多难 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:26

    I don't know if there is an existing method but you could use the following (null checking of args omitted for brevity)

    public static bool DictionaryEquals(
      this Dictionary left,
      Dictionary right ) { 
    
      var comp = EqualityComparer.Default;
      if ( left.Count != right.Count ) { 
        return false;
      }
      foreach ( var pair in left ) {
        TValue value;
        if ( !right.TryGetValue(pair.Key, out value) 
             || !comp.Equals(pair.Value, value) ) {
          return false;
        }
      } 
      return true;
    }
    

    It would be best to add an overload to allow customization of the EqualityComparer.

提交回复
热议问题