Created
December 9, 2013 16:00
-
-
Save btjake/7874492 to your computer and use it in GitHub Desktop.
AddOrUpdate method for IDictionary since none exists for some reason
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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