Skip to content

Instantly share code, notes, and snippets.

@btjake
Created December 9, 2013 16:00
Show Gist options
  • Save btjake/7874492 to your computer and use it in GitHub Desktop.
Save btjake/7874492 to your computer and use it in GitHub Desktop.
AddOrUpdate method for IDictionary since none exists for some reason
void Main()
{
Dictionary<int, int> dict = new Dictionary<int, int>();
Random rndm = new Random();
for(int i = 0; i < 100; i++)
{
int foo = rndm.Next(10);
dict.AddOrUpdate(foo, 1, (val) => { return val+=1; });
}
foreach(var key in dict.Keys)
{
Console.WriteLine("{0} = {1}", key, dict[key]);
}
}
public static class Extensions
{
public static void AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<TKey, TValue> defaultValue, Func<TValue, TValue> updateOperation)
{
if(dict.ContainsKey(key))
{
dict[key] = updateOperation(dict[key]);
} else {
dict.Add(key, defaultValue(key));
}
}
public static void AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue, Func<TValue, TValue> updateOperation)
{
dict.AddOrUpdate(key, (k) => { return defaultValue; }, updateOperation);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment