Update Dictionary Value field through loop
本问题已经有最佳答案,请猛点这里访问。
我定义了一个
1 |
现在我想更新我的值:
1 2 3 4 5 | foreach (KeyValuePair<string, double> pair int collection) { double val = 3.0; collection[pair.Value] = val; // Get an error } |
号
我的错误是无法从double转换为string。为什么?
不能在
您需要复制集合,并修改复制的版本…示例如下:
1 2 3 4 5 6 7 8 9 10 11 12 | Dictionary<string, double> collection = new Dictionary<string, double>(); collection.Add("A", 1.0); collection.Add("B", 2.0); Dictionary<string, double> collection2 = new Dictionary<string, double>(collection); foreach (KeyValuePair<string, double> pair in collection) { double val = 3.0; collection2.Remove(pair.Key); collection2.Add(pair.Key, val); } |
号
试试这个
1 2 3 4 5 6 | Dictionary<string, double> Copycollection= new Dictionary<string, double> (collections); foreach (KeyValuePair<string, double> pair in Copycollection) { double val = 3.0; collection[pair.Key] = val; } |