.NET Dictionary: get or create new
If you use .Net Core you can use Dictionary<>.TryAdd()
.
var dict = new Dictionary<string, string>();
dict.TryAdd("foo", "bar"); // returns bool whether it added or not feel free to ignore.
var myValue = dict["foo"];
We have a slightly different take on this, but the effect is similar:
public static TValue GetOrCreate<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key)
where TValue : new()
{
if (!dict.TryGetValue(key, out TValue val))
{
val = new TValue();
dict.Add(key, val);
}
return val;
}
Called:
var dictionary = new Dictionary<string, List<int>>();
List<int> numbers = dictionary.GetOrCreate("key");
It makes use of the generic constraint for public parameterless constructors: where TValue : new()
.
To help with discovery, unless the extension method is quite specific to a narrow problem, we tend to place extension methods in the namespace of the type they are extending, in this case:
namespace System.Collections.Generic
Most of the time, the person using the type has the using
statement defined at the top, so IntelliSense would also find the extension methods for it defined in your code.
As with so many programming problems, when you find yourself doing something a lot, refactor it into a method:
public static void MyAdd<TKey, TCollection, TValue>(
this Dictionary<TKey, TCollection> dictionary, TKey key, TValue value)
where TCollection : ICollection<TValue>, new()
{
TCollection collection;
if (!dictionary.TryGetValue(key, out collection))
{
collection = new TCollection();
dictionary.Add(key, collection);
}
collection.Add(value);
}