通过循环更新字典值字段
本文关键字:字段 字典 更新 循环 | 更新日期: 2023-09-27 18:15:33
我定义了一个Dictionary
如下:
Dictionary<string, double> collection = new Dictionary<string, double>();
现在我想更新我的值:
foreach (KeyValuePair<string, double> pair int collection)
{
double val = 3.0;
collection[pair.Value] = val; // Get an error
}
我的错误是不能从双精度转换到字符串。为什么?
不能在迭代Dictionary
时改变其内部值,因为这会破坏迭代器。
您需要复制集合,并修改复制的版本…在下面的例子:
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);
}
试试这个
Dictionary<string, double> Copycollection= new Dictionary<string, double> (collections);
foreach (KeyValuePair<string, double> pair in Copycollection)
{
double val = 3.0;
collection[pair.Key] = val;
}