Further to Pete's excellent answer, you can use
the TryGetValue
method[
^] to avoid the double key lookup of
ContainsKey
followed by the indexer:
if (!uniqueComp.TryGetValue(cmp1[i].name, out List<object> list))
{
list = new List<object>();
uniqueComp.Add(cmp1[i].name, list);
}
list.Add(...);
You could even turn this pattern into an extension method, inspired by
the ConcurrentDictionary<TKey, TValue>
's GetOrAdd
method[
^]:
public static class DictionaryExtensions
{
public static TValue GetOrAdd<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
TKey key,
Func<TKey, TValue> valueFactory)
{
if (!dictionary.TryGetValue(key, out TValue value))
{
value = valueFactory(key);
dictionary.Add(key, value);
}
return value;
}
}
which would then make your code:
List<object> list = uniqueComp.GetOrAdd(cmp1[i].name, _ => new List<object>());
list.Add(...);