Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

c# - Comparing 2 Dictionary<string, string> Instances

I want to compare the contents of two Dictionary<string, string> instances regardless of the order of the items they contain. SequenceEquals also compares the order, so I first order the dictionaries by key and then call SequenceEquals.

Is there a method that I can use instead of SequenceEquals that will only compare the contents?

If there isn't, is this the ideal way to do this?

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));
question from:https://stackoverflow.com/questions/3928822/comparing-2-dictionarystring-string-instances

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...