比较2 Dictionary <string,string =“”> Instances </string,>

时间:2010-10-13 23:16:01

标签: c# linq dictionary comparison

我想比较两个Dictionary<string, string>实例的内容,而不管它们包含的项目的顺序如何。 SequenceEquals也会对顺序进行比较,因此我首先按键排序字典,然后调用SequenceEquals

是否有一种我可以使用的方法,而不是仅仅比较内容的SequenceEquals

如果没有,这是理想的做法吗?

Dictionary<string, string> source = new Dictionary<string, string>();
Dictionary<string, string> target = new Dictionary<string, string>();

source["foo"] = "bar";
source["baz"] = "zed";
source["blah"] = null;

target["baz"] = "zed";
target["blah"] = null;
target["foo"] = "bar";

// sequenceEquals will be false
var sequenceEqual = source.SequenceEqual(target);
// contentsEqual will be true
var contentsEqual = source.OrderBy(x => x.Key).SequenceEqual(target.OrderBy(x => x.Key));

4 个答案:

答案 0 :(得分:53)

var contentsEqual = source.DictionaryEqual(target);

// ...

public static bool DictionaryEqual<TKey, TValue>(
    this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second)
{
    return first.DictionaryEqual(second, null);
}

public static bool DictionaryEqual<TKey, TValue>(
    this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second,
    IEqualityComparer<TValue> valueComparer)
{
    if (first == second) return true;
    if ((first == null) || (second == null)) return false;
    if (first.Count != second.Count) return false;

    valueComparer = valueComparer ?? EqualityComparer<TValue>.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;
}

答案 1 :(得分:6)

我不知道是否存在现有方法,但您可以使用以下方法(为了简洁省略了args的空检查)

public static bool DictionaryEquals<TKey,TValue>(
  this Dictionary<TKey,TValue> left,
  Dictionary<TKey,TValue> right ) { 

  var comp = EqualityComparer<TValue>.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;
}

最好添加一个重载以允许自定义EqualityComparer<TValue>

答案 2 :(得分:0)

如果您使用SortedDictionary,则无需自行应用排序,这可能会更容易使用:

void Main()
{
    var d1 = new Dictionary<string, string>
    {
        ["a"] = "Hi there!",
        ["b"] = "asd",
        ["c"] = "def"
    };
    var d2 = new Dictionary<string, string>
    {
        ["b"] = "asd",
        ["a"] = "Hi there!",
        ["c"] = "def"
    };

    var sortedDictionary1 = new SortedDictionary<string, string>(d1);
    var sortedDictionary2 = new SortedDictionary<string, string>(d2);

    if (sortedDictionary1.SequenceEqual(sortedDictionary2))
    {
        Console.WriteLine("Match!");
    }
    else
    {
        Console.WriteLine("Not match!");
    }
}

答案 3 :(得分:-1)

这将检查Values中是否存在source的所有target,忽略了Keys

var result = source.All(x => target.Any(y => x.Value == y.Value));
相关问题