title: .NET Dictionary: get or create new
body: <p>I often find myself creating a <a href="http://msdn.microsoft.com/en-us/library/xfhwa508.aspx" rel="noreferrer"><code>Dictionary</code></a> with a non-trivial value class (e.g. <a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx" rel="noreferrer"><code>List</code></a>), and then always writing the same code pattern when filling in data.</p>
  
  <p>For example:</p>
  
  <pre class="lang-csharp prettyprint-override"><code>var dict = new Dictionary&lt;string, List&lt;string&gt;&gt;();
  string key = "foo";
  string aValueForKey = "bar";
  </code></pre>
  
  <p>That is, I want to insert <code>"bar"</code> into the list that corresponds to key <code>"foo"</code>, where key <code>"foo"</code> might not be mapped to anything.</p>
  
  <p>This is where I use the ever-repeating pattern:</p>
  
  <pre class="lang-csharp prettyprint-override"><code>List&lt;string&gt; keyValues;
  if (!dict.TryGetValue(key, out keyValues))
    dict.Add(key, keyValues = new List&lt;string&gt;());
  keyValues.Add(aValueForKey);
  </code></pre>
  
  <p>Is there a more elegant way of doing this?</p>
  
  <p>Related questions that don't have answers to this question:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/q/538729/974531">Is there an IDictionary implementation that returns null on missing key instead of throwing?</a></li>
  <li><a href="https://stackoverflow.com/q/6408916/974531">Find-or-insert with only one lookup in c# dictionary</a></li>
  <li><a href="https://stackoverflow.com/q/2601477/974531">Dictionary returning a default value if the key does not exist</a></li>
  </ul>