Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can actually use the others' suggestions. By encapsulating the access in a method or even using ConcurrentDictionary.</p> <p>But for me, <strong>I would have a custom dictionary</strong> so you can actually implement what <code>myDict["entry"]</code> does if it did not see an element.</p> <p><em>Good thing with this is you have full control on how you would like this dictionary to behave.</em></p> <pre><code>class MyCustomDictionary&lt;TKey, TValue&gt; : IDictionary&lt;TKey, TValue&gt; where TValue : class, new() { private Dictionary&lt;TKey, TValue&gt; _dictionary; public MyCustomDictionary() { _dictionary = new Dictionary&lt;TKey, TValue&gt;(); } public TValue this[TKey key] // this is what's important { get { TValue val; if (!_dictionary.TryGetValue(key, out val)) // if there is no element for that key, add a new element and return it { _dictionary.Add(key, new TValue()); return _dictionary[key]; } else // else return the found element { return val; } } set { _dictionary[key] = value; } } public void Add(TKey key, TValue value) { _dictionary.Add(key, value); } public bool ContainsKey(TKey key) { return _dictionary.ContainsKey(key); } public ICollection&lt;TKey&gt; Keys { get { return _dictionary.Keys; } } public bool Remove(TKey key) { return _dictionary.Remove(key); } public bool TryGetValue(TKey key, out TValue value) { return _dictionary.TryGetValue(key, out value); } public ICollection&lt;TValue&gt; Values { get { return _dictionary.Values; } } public void Add(KeyValuePair&lt;TKey, TValue&gt; item) { _dictionary.Add(item.Key, item.Value); } public void Clear() { _dictionary.Clear(); } public bool Contains(KeyValuePair&lt;TKey, TValue&gt; item) { return _dictionary.Contains(item); } public void CopyTo(KeyValuePair&lt;TKey, TValue&gt;[] array, int arrayIndex) { _dictionary.ToList().CopyTo(array, arrayIndex); // do you need this? you can leave this :) } public int Count { get { return _dictionary.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(KeyValuePair&lt;TKey, TValue&gt; item) { return _dictionary.Remove(item.Key); } public IEnumerator&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; GetEnumerator() { return _dictionary.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _dictionary.GetEnumerator(); } } </code></pre> <p>Then you use it like:</p> <pre><code>MyCustomDictionary&lt;string, List&lt;int&gt;&gt; myCustomDict = new MyCustomDictionary&lt;int, List&lt;int&gt;&gt;(); // return a new List of int var someElementThatIsNotFound = myCustomDict["keyThatIsNonExistent"]; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload