- Home /
Question by
SFoxx28 · Dec 29, 2017 at 04:24 AM ·
c#unity 5programming
how do I compare all the keys and values from one dictionary to another?
Title
The myDictionary.Equals(object) function just isn't working for me so I need a better solution. Does anyone know of a way to do this? It sounds simple but I've been working on it for the longest while and I still haven't figured it out yet.
Thanks and any help you can give.
Happy Holidays
Comment
Something like this:
foreach($$anonymous$$eyValuePair<$$anonymous$$eyType,ValueType> pair in myDictionary) {
foreach($$anonymous$$eyValuePair<$$anonymous$$eyType,ValueType> pair2 in myOtherDictionary) {
if(pair.$$anonymous$$ey == pair2.$$anonymous$$ey) {
}
if(pair.Value== pair2.Value) {
}
}
}
$$anonymous$$aybe you could even compare the pairs directly.
Best Answer
Answer by SFoxx28 · Dec 29, 2017 at 04:55 AM
Nevermind, a bit more searching on the net and I found this VERY useful C# script that does the trick wonderfully.
public bool CompareX<TKey, TValue>(
Dictionary<TKey, TValue> dict1, Dictionary<TKey, TValue> dict2)
{
if (dict1 == dict2) return true;
if ((dict1 == null) || (dict2 == null)) return false;
if (dict1.Count != dict2.Count) return false;
var valueComparer = EqualityComparer<TValue>.Default;
foreach (var kvp in dict1)
{
TValue value2;
if (!dict2.TryGetValue(kvp.Key, out value2)) return false;
if (!valueComparer.Equals(kvp.Value, value2)) return false;
}
return true;
}