Reputation: 445
Using C#, I want to compare two dictionaries to be specific, two dictionaries with the same keys but not same values, I found a method Comparer but I'm not quite sure how can I use it? Is there a way other than iterating through each key?
Dictionary
[
{key : value}
]
Dictionary1
[
{key : value2}
]
Upvotes: 16
Views: 24871
Reputation: 4915
I think this is fastest way to check the differences between keys apart from count.
var isTrue = !dict1.Keys.Any(k => !dict2.Keys.Contains(k)) &&
!dict2.Keys.Any(k => !dict1.Keys.Contains(k));
Upvotes: 0
Reputation: 52157
You could just:
new HashSet<TKey>(dictionary1.Keys).SetEquals(dictionary2.Keys)
Be careful if dictionary1
uses a different comparer from dictionary2
. You'll have to decide whether "equality" means what one or the other dictionary thinks it means (or something else entirely)...
Upvotes: 0
Reputation: 111
return dict1.Count == dict2.Count &&
dict1.Keys.All(dict2.ContainsKey);
Upvotes: 11
Reputation: 55298
Try this
public bool SameKeys<TKey, TValue>(IDictionary<TKey, TValue> one, IDictionary<TKey, TValue> two)
{
if (one.Count != two.Count)
return false;
foreach (var key in one.Keys)
{
if (!two.ContainsKey(key))
return false;
}
return true;
}
Upvotes: 1
Reputation: 141703
If all you want to do is see if the keys are different but not know what they are, you can use the SequenceEqual
extension method on the Keys
property of each dictionary:
Dictionary<string,string> dictionary1;
Dictionary<string,string> dictionary2;
var same = dictionary1.Count == dictionary2.Count && dictionary1.Keys.SequenceEqual(dictionary2.Keys);
If you want the actual differences, something like this:
var keysDictionary1HasThat2DoesNot = dictionary1.Keys.Except(dictionary2.Keys);
var keysDictionary2HasThat1DoesNot = dictionary2.Keys.Except(dictionary1.Keys);
Upvotes: 27
Reputation: 7515
You could go with this (depending if you want the intersect or the exclusion):
Dictionary<int, int> dict1 = new Dictionary<int, int>();
Dictionary<int, int> dict2 = new Dictionary<int, int>();
IEnumerable<int> keys1ExceptKeys2 = dict1.Keys.Except(dict2.Keys);
IEnumerable<int> keys2ExceptKeys1 = dict2.Keys.Except(dict1.Keys);
IEnumerable<int> keysIntersect = dict1.Keys.Intersect(dict2.Keys);
Upvotes: 0
Reputation: 5983
You can get a collection of the keys and index it, if that helps.
dictionary1.keys[0] == dictionary2.keys[5]
I'm actually not sure if you index it with a number or if you do it with the key itself, so try out both.
Upvotes: 0