3

i have two Dictionarys A & B, i want to see if all entries in A exist in B. In the past i've compared Lists using the following:

var set1 = new HashSet<String>(list1);
var set2 = new HashSet<String>(list2);

return set1.SetEquals(set2);

What i have thought to do is simply loop over each value in Dictionary A using:

dictA.TryGetValue(dictBvalue, out item)

this will return null on the item var if the value isn't there, but this seems a little long winded.

Is there a quick and effcient way of comparing dictionaries?

Thanks.

Dan Hall
  • 1,474
  • 2
  • 18
  • 43

3 Answers3

4

You could use All extension and do this.

var allexist = list1.All(x=> list2.ContainsKey(x.Key) && list2[x.Key] == x.Value)
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
  • Typo, it shuold be `x` :-) – Hari Prasad Mar 31 '16 at 09:20
  • this does what i need quickly and effciently, thanks :) – Dan Hall Mar 31 '16 at 09:31
  • Just to clarify, if all items in list1 are in list2 then this returns true, if any of the items in list1 do not occur in list2 then it returns false? – Dan Hall Mar 31 '16 at 09:37
  • Thank you :) Just one more question for you, is there anyway to output the keys from list1 that were not found in list2 to a new list using the same simple approach as above? – Dan Hall Mar 31 '16 at 09:51
  • use this `list1.Keys.Where(k=>!list2.ContainsKey(k)).ToList()` this returns keys in list1 which are not there in list2. – Hari Prasad Mar 31 '16 at 09:54
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/107838/discussion-between-dan-hall-and-hari-prasad). – Dan Hall Mar 31 '16 at 10:16
0

here is the solution if you want to loop over each value

Dictionary<string, string> dictA = new Dictionary<string, string>();
Dictionary<string, string> dictB = new Dictionary<string, string>();
bool allexist = true;

foreach (var itemA in dictA)
{
    if (!dictB.ContainsKey(itemA.Key))
    {
        allexist = false;
    }
}
Byyo
  • 2,163
  • 4
  • 21
  • 35
  • There are **lots** of optimizations possible, compare it with [DictionaryEquals method from this answer](http://stackoverflow.com/questions/3928822/comparing-2-dictionarystring-string-instances/3928856#3928856) – synek317 Mar 31 '16 at 11:49
0

Actually, you asked for a method comparing dictionaries but your code example refer to HashSet which is different.

For HashSets, you can use IsSubsetOf and SetEquals methods.

To compare dictionaries, you can use DictionaryEquals method from this answer

Community
  • 1
  • 1
synek317
  • 749
  • 2
  • 7
  • 22
  • That was just an example of what i would do with lists, in this case i'm looking for a similar solution for dictionaries. I'll check that link, thanks. – Dan Hall Mar 31 '16 at 09:21