Kristoffer Rasmussen Kristoffer Rasmussen - 29 days ago 10
C# Question

How to count occurrences of int value in nested dictionary in c#

I have a dictionary looking

Dictionary<string, Dictionary<string, int>> personStats


In my code it automatically generate new "persons" (keys) with a specific set of keys + values. First "string" is name and in the nested dictionary you have strings like "age", "height", "gender" with an attached int-value.

Example: John age: 20, height: 180, gender: 0 (0 is for male).

In my case I would like to count how many times a specific int-value on a specific string occur. Example: I have a 100 persons (keys) in the dictionary, and I would like to know how many persons have the exact "age" of 43.

I've tried using
.Count
. Example:
personStats.Count()
, but of course it counts the first string (not to mention it doesn't take into account i want to cound a specific int-value). I've also tried with foreach, but I have no idea how to enter the nested dictionary to find the string "

Edit: Example of how I generate new keys. The parameters(personname,statType,value) comes from other methodes.

public void SetPersonStats(string personname, string statType, int value)
{

if (personStats.ContainsKey(personname) == false)
{
personStats[personname] = new Dictionary<string, int>();
}

personStats[personname][statType] = value;
}


So the parameters could be (John, age, 20), and (John, height, 180), and (John, gender, 0). So in the end I'll end up with the entry(?) John with 3 attached strings+value: age=20,heigh=180,gender=0. So imagine I ran this 100 times and got 100 different names with random ages, and I wanted to count how many had the age of 43.

Answer

This should fetch you the number of users with age 42:

personStats.Count(c => c.Value["age"] == 42);

Ideally though, you should be using a class to define the person. Something like

enum Gender
{
     Male,
     Female
}
class PersonStats
{
    int Age;
    int Height;
    Gender Gender;
}


//Add to the dictionary
var dict = Dictionary<string, PersonStats>();
dict.Add("FrankerZ", new PersonStats{
   Age = 28,
   Height = 180,
   Gender = Gender.Male
});

//Some example filters:
dict.Count(person => person.Age == 28); //1
dict.Count(person => person.Gender == Gender.Male); //1