Created
November 27, 2013 08:07
-
-
Save distantcam/7672219 to your computer and use it in GitHub Desktop.
Dictionary Extensions
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
using System; | |
using System.Linq; | |
namespace System.Collections.Generic | |
{ | |
public static class DictionaryExtensions | |
{ | |
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TValue> valueFactory) | |
{ | |
TValue v; | |
if (dictionary.TryGetValue(key, out v)) | |
{ | |
return v; | |
} | |
else | |
{ | |
v = valueFactory(key); | |
dictionary.Add(key, v); | |
return v; | |
} | |
} | |
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value) | |
{ | |
TValue v; | |
if (dictionary.TryGetValue(key, out v)) | |
{ | |
return v; | |
} | |
else | |
{ | |
dictionary.Add(key, value); | |
return value; | |
} | |
} | |
public static TValue AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory) | |
{ | |
TValue v; | |
TValue newValue; | |
if (dictionary.TryGetValue(key, out v)) | |
{ | |
newValue = updateValueFactory(key, v); | |
dictionary[key] = newValue; | |
} | |
else | |
{ | |
newValue = addValueFactory(key); | |
dictionary.Add(key, newValue); | |
} | |
return newValue; | |
} | |
public static TValue AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory) | |
{ | |
TValue v; | |
TValue newValue; | |
if (dictionary.TryGetValue(key, out v)) | |
{ | |
newValue = updateValueFactory(key, v); | |
dictionary[key] = newValue; | |
} | |
else | |
{ | |
newValue = addValue; | |
dictionary.Add(key, newValue); | |
} | |
return newValue; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment