c# - List<T> 如何与 Dictionary<K, List<T>> 一起工作?

标签 c# algorithm

var solutions = new Dictionary<int, List<Tuple<int, int>>>();

List<Tuple<int, int>> list = null;

var z = solutions.TryGetValue(sum, out list);
if (!z)
{
   list = new List<Tuple<int, int>>();
   solutions.Add(sum, list);
}

list.Add(new Tuple<int, int>(a, b));

我不明白为什么当我将元素添加到列表(最后一行)时它会更改字典中相应的键值?

最佳答案

您不会通过向列表添加元素来更改字典中的键值对。您正在更改列表。字典只是保留对该列表的引用,因此它似乎发生了变化。

关于c# - List<T> 如何与 Dictionary<K, List<T>> 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37882769/

相关文章:

c# - Rdlc 导出到 excel 问题 : when group is added with details

c# - 如何快速找到我的 EDMX 模型中的特定表?

algorithm - 给定欧几里德距离范围的分区邻居点

algorithm - 为什么递归归并排序优于迭代归并排序,即使后者具有辅助空间复杂性?

c# - 为什么我的 DataClassesDataContext 没有默认构造函数?

C# 使用内存映射文件

c# - 哈希码非零初始值 - 注意 : I am not asking about primes

c++ - 在增量凸包 3D 期间获取点的地平线

algorithm - 有没有一种算法可以找到文本的香农熵?

algorithm - 获取数字的所有因子(迭代器摊牌 :)