我已定义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
}
我的错误是无法从double转换为字符串。 那是为什么?
答案 0 :(得分:2)
您不能迭代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);
}
答案 1 :(得分:0)
试试这个
Dictionary<string, double> Copycollection= new Dictionary<string, double> (collections);
foreach (KeyValuePair<string, double> pair in Copycollection)
{
double val = 3.0;
collection[pair.Key] = val;
}