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:
var dict = new Dictionary<string, List<string>>();
string key = "foo";
string aValueForKey = "bar";
That is, I want to insert "bar"
into the list that corresponds to key "foo"
, where key "foo"
might not be mapped to anything.
This is where I use the ever-repeating pattern:
List<string> keyValues;
if (!dict.TryGetValue(key, out keyValues))
dict.Add(key, keyValues = new List<string>());
keyValues.Add(aValueForKey);
Is there a more elegant way of doing this?
Related questions that don't have answers to this question:
- Is there an IDictionary implementation that returns null on missing key instead of throwing?
- Find-or-insert with only one lookup in c# dictionary
- Dictionary returning a default value if the key does not exist