c# - C# 中带有列表的默认字典

标签 c# dictionary

有没有办法让 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/

相关文章:

c# - 从 VB.NET 编码过渡到 C# 的好练习?

c# - 在实体值更新期间读取值?

C# 可空值类型产生垃圾?

javascript - 在排序的 JavaScript 字典中查找前 3 个值条目?

c# - 为什么在个人类(class)上使用字典时不需要重写 GetHashCode?

python - 字典元素之间的欧氏距离

c# - 如何使用 C# 在 Windows Phone 8.1 中将图像转换为字节数组

python - 从字典中的所有值中减去 1

python - 通过强制转换从 Dict 设置类的属性

c# - 围绕存储过程自动创建 C# 包装器类