Search code examples
c#dictionarydefault

Count things with a dictonary without permanently check for existance?


Today I use code like this to count things:

Dictionary<string,int> wordCount = new Dictionary<string,int>();
if (!wordCount.ContainsKey(word))
{
    wordCount.Add(word, 0);
}
wordCount[word]++;

Is there a more elegant way to count things without permanently check existence?

I would like to do something like:

Dictionary<string,int> wordCount = new Dictionary<string,int>();
wordCount[word]++;

And values for the new key should automatically be initialized with a default value (0 for int for example).

Is there an elegant way to have this?

Thanks in advance.


Solution

  • You could define an extension method for dictionaries like this:

    public static class DictionaryExtension
    {
        public static void AddCount<T>(this Dictionary<T, int> dict, T key)
        {
            if (dict.ContainsKey(key))
            {
                dict[key]++;
            }
            else
            {
                dict[key] = 1;
            }
        }
    }
    

    You can then use it like this:

    Dictionary<string, int> count = new Dictionary<string, int>();
    count.AddCount("foo");
    count.AddCount("bar");
    count.AddCount("foo");
    

    To go further, you could derive a new type from Dictionary and introduce a new indexer:

    public class FancyDict<T> : Dictionary<T,int>
    {
        public new int this[T key]
        {
            get => this.ContainsKey(key) ? base[key] : 0;
            set => base[key] = value;
        }
    }
    

    This makes it possible to use the [] syntax:

    FancyDict<string> fancyCount = new FancyDict<string>();
    fancyCount["foo"]++;
    fancyCount["bar"]++;
    fancyCount["foo"]++;
    
    foreach (var key in fancyCount.Keys)
    {
        Console.WriteLine(key + " : " + fancyCount[key]);
    }