简体   繁体   中英

Finding the number of odd/even values in a dictionary

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?

使用 LINQ:

var numOdd = myDic.Count(e => e.Value % 2 == 1);

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM