ExtensionMethod.NET Home of 818 C#, Visual Basic, F# and Javascript extension methods

IncrementAt<T>

Increment counter at the key passed as argument. Dictionary is <TKey, Int>

Source

using System.Collections.Generic;

namespace KMorcinek.Common
{
    public static class DictionaryExtensions
    {
        public static void IncrementAt<T>(this Dictionary<T, int> dictionary, T index)
        {
            int count = 0;

            dictionary.TryGetValue(index, out count);

            dictionary[index] = ++count;
        }
    }
}

Example

var animalQuantities = new Dictionary<string, int>();
animalQuantities.IncrementAt("cat");
animalQuantities.IncrementAt("cat");

Console.WriteLine(animalQuantities["cat"]); // 2

Author: Krzysztof Morcinek

Submitted on: 28 okt 2012

Language: C#

Type: System.Collections.Generic.Dictionary

Views: 3422