1

I have a dictionary, let's it key value pair be as follow:

a - 1
b - 3
c - 2

I want to find out the number of odd and even value chars. For example, the above will return me 2 odd and 1 even.

I was thinking of iterating but I read iterating is the wrong way if we are using a dictionary. What is the best approach?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
John
  • 123
  • 1
  • 8
  • 2
    Where did you read " iterating is the wrong way if we are using a dictionary"? If iterating over a dictionary is bad then it probably wouldn't implement IEnumerable/Enumerator. – Tdorno Jun 05 '16 at 03:00
  • one stackover flow comment before writing this question. sorry, don't have the link though – John Jun 05 '16 at 03:16
  • Those values are integer not char. Value in Dictionary is not indexed. – paparazzo Jun 05 '16 at 03:17

2 Answers2

4

use LINQ:

var numOdd = myDic.Count(e => e.Value % 2 == 1);
Mike Tsayper
  • 1,686
  • 1
  • 17
  • 25
  • 2
    @John It's still iterating over the dictionary, though (granted I don't think it's possible to avoid iterating over the dictionary and do what you want) – Casey Jun 05 '16 at 03:21
0

See this link What is the best way to iterate over a Dictionary in C#? , iterating internally or externally is needed.

The code should be something like following. It first identifies the number of evens, then the number of odd will be total elements minus event numbers.

 int evenCounter=0; 
   foreach(var item in myDictionary.Values)
    {
      if(item %2 ==0)
       evenCounter++;
    }

    int oddCounter = myDictionary.Count -evenCounter;
Community
  • 1
  • 1
Memin
  • 3,788
  • 30
  • 31
  • Alright, I did the same too but was told you shouldn't use a dictionary when it comes to iterating. oh well.. – John Jun 05 '16 at 03:02
  • This is exactly what the OP said they thought about doing but are asking about a different approach. – jdphenix Jun 05 '16 at 03:02
  • We don't need keys for identifying the number of odds, so you can simply use arrays to store, and just iterate over the arrays, if you like it. – Memin Jun 05 '16 at 03:04