-1

I have Two Dictionary DictA & DictB such as:

Dictionary<int, string> DictA = new Dictionary<int, string>();
DicA.add(1,"Mango");
DicA.add(2,"Grapes");
DicA.add(3,"Orange");

Dictionary<int, string> DictB = new Dictionary<int, string>();
DicB.add(1,"Mango");
DicB.add(2,"Pineapple");

How to Compare the values of these Two Dictionary DictA key,value with DictB key,value and if MATCH IS FOUND then INCREMENT the COUNTER variable.

Note: DicA may Contains many Rows as compared to DicB EG: DicA has 3 Rows and DicB has 2 Rows. If DicA key,value match(similar/equal) to DicB key,val then increment the counter variable by one!

Any Suggestion..! Help Appreciated...!

SHEKHAR SHETE
  • 5,964
  • 15
  • 85
  • 143

2 Answers2

3

Use this code:

int matches = DictA.Keys.Where(k => DictB.ContainsKey(k) && DictB[k] == DictA[k]).Count();
Adam
  • 26,549
  • 8
  • 62
  • 79
1

You could use:

Dictionary<int, string> DicA = new Dictionary<int, string>();
DicA.Add(1,"Mango");
DicA.Add(2,"Grapes");
DicA.Add(3,"Orange");

Dictionary<int, string> DicB = new Dictionary<int, string>();
DicB.Add(1,"Mango");
DicB.Add(2,"Pineapple");

int counter = 0;

foreach (var pair in DicA)
{
     string value;

     if (DicB.TryGetValue(pair.Key, out value))
     {
          if (value == pair.Value)
          {
                counter++;
          }
     }
}
dtsg
  • 4,408
  • 4
  • 30
  • 40
  • It compiles fine for me, i'm guessing you just cut and pasted it without checking variable names... But yes @SamLeach, value should be a string. – dtsg Jun 26 '12 at 13:49
  • just i want to inform you that it gives error dont misunderstand..! – SHEKHAR SHETE Jun 26 '12 at 14:04
  • What specific error does it throw? I ran this exact code on my machine and the value of `counter` returns `1` as expected. – dtsg Jun 26 '12 at 14:05
  • you have edited your code ur previous code is: foreach (var pair in DictA) { int value; if (DictB.TryGetValue(pair.Key, out value)) { if (value == pair.Value) { counter++; } } } – SHEKHAR SHETE Jun 26 '12 at 14:11
  • Yes, I know. @SamLeach kindly pointed out that `value` should be a string. – dtsg Jun 26 '12 at 14:12