I often find myself creating a Dictionary with a non-trivial value class (e.g. List), and then always writing the same code pattern when filling in data.
For example
Here is a solution in case the constructor requires a parameter.
public static TValue GetOrCreate(this IDictionary dict, TKey key, Func createNew)
{
if (!dict.TryGetValue(key, out var val))
{
val = createNew();
dict.Add(key, val);
}
return val;
}
Simple to use:
MyDict.GetOrCreate(si.Id, createNew: () => new ObjectKnowingItsId(si.Id))