Abby Howe
Abby Howe

Reputation: 86

Add & Increment the Key and Value in C# dictionary

I'm creating a counter that counts the number of times each character occurs in a string and then prints the results to the console.

Let's use this sample string:

string myString = "The pen is mightier."

I want the results to be

T : 2
h : 2
e : 3
  : 2
p : 1
n : 1
i : 3
s : 1
m : 1
g : 1
r : 1
. : 1

I've converted the string to a character array.

char[] charactersInString = myString.ToCharArray();

I've created a dictionary that stores the letters and the count.

Dictionary<char, int> letters = new Dictionary<char, int>();

I loop through each letter in the characterInString array and am not sure how to initialize and add a new pair when the dictionary doesn't contain the key or how to update the value only when it does contain the key?

Upvotes: 1

Views: 3601

Answers (1)

John Wu
John Wu

Reputation: 52210

Pretty easy with LINQ.

var dictionary = myString.GroupBy( x => x ).ToDictionary( x => x.Key, x => x.Count );

If you want to count lower and upper case as the same, coerce the string to uppercase beforehand:

var dictionary = myString.ToUpper().GroupBy( x => x ).ToDictionary( x => x.Key, x => x.Count );

If you want to do it the traditional way, you'll need a loop.

var dictionary = new Dictionary<char,int>();
foreach (var character in myString.ToUpper())
{
    if (dictionary.ContainsKey(character)) 
    {
        dictionary[character]++;
    }
    else
    {
        dictionary.Add(character, 1);
    }
}

Upvotes: 3

Related Questions