Can I compare the keys of two dictionaries?
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 t开发者_Python百科hrough each key?
Dictionary
[
{key : value}
]
Dictionary1
[
{key : value2}
]
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);
return dict1.Count == dict2.Count &&
dict1.Keys.All(dict2.ContainsKey);
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;
}
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.
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);
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)...
精彩评论