Created
February 20, 2014 21:12
-
-
Save paulblamire/9123271 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.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace Everhaven.Utility | |
{ | |
internal static class DictionaryExtensions | |
{ | |
public static V GetOrNull<K, V>(this Dictionary<K, V> dictionary, K key) | |
{ | |
V existingValue; | |
if (dictionary.TryGetValue(key, out existingValue)) | |
{ | |
return existingValue; | |
} | |
else | |
{ | |
return default(V); | |
} | |
} | |
public static V GetOrCreate<K, V>(this Dictionary<K, V> dictionary, K key, Func<V> valueFactory) | |
{ | |
if (key == null) throw new ArgumentException("get or create must supply a key for the dictionary"); | |
V existingValue; | |
if (!dictionary.TryGetValue(key, out existingValue)) | |
{ | |
V newValue = valueFactory(); | |
dictionary.Add(key, newValue); | |
return newValue; | |
} | |
else | |
{ | |
return existingValue; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment