有没有办法让 C# 中的 Dictionary
自动具有与任何键关联的空列表,而不是自己创建这样一个类?如果可能的话,我想避免使用以下代码:
int x = 0;
int y = 42;
Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();
List<int> newList;
if (dict.containsKey(x))
{
dict[x].Add(y);
}
else
{
dict[x] = new List<int>{y};
}
或者可能:
int x = 0;
int y = 42;
Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();
List<int> newList;
if (dict.TryGetValue(x, out newList))
{
newList.Add(y);
}
else
{
dict[x] = new List<int>{y};
}
最佳答案
可以使用扩展方法很好地抽象此行为。
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TValue> valueFactory)
{
if (dictionary == null) throw new ArgumentNullException(nameof(dictionary));
if (valueFactory == null) throw new ArgumentNullException(nameof(valueFactory));
TValue value;
if (!dictionary.TryGetValue(key, out value))
{
value = valueFactory.Invoke(key);
dictionary.Add(key, value);
}
return value;
}
方法签名与ConcurrentDictionary.GetOrAdd()
相同。
var list = dict.GetOrAdd(x, (_) => new List<int>());
list.Add(y);
关于c# - C# 中带有列表的默认字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47081502/