如何通过词典和变化值循环? [英] How to iterate through Dictionary and change values?
本文介绍了如何通过词典和变化值循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Dictionary<string,double> myDict = new Dictionary();
//...
foreach (KeyValuePair<string,double> kvp in myDict)
{
kvp.Value = Math.Round(kvp.Value, 3);
}
我得到一个错误:
属性或索引System.Collections.Generic.KeyValuePair.Value'不能被分配到 - 它是只读的。
我怎样才能通过 myDict
迭代和变化值?
I get an error:
"Property or indexer 'System.Collections.Generic.KeyValuePair.Value' cannot be assigned to -- it is read only."
How can I iterate through myDict
and change values?
推荐答案
根据 MSDN
foreach语句是一个包装 周围的枚举,这使得 从集合只读,不能 写吧。
The foreach statement is a wrapper around the enumerator, which allows only reading from the collection, not writing to it.
使用这样的:
var dictionary = new Dictionary<string, double>();
var keys = new List<string>(dictionary.Keys);
foreach (string key in keys)
{
dictionary[key] = Math.Round(dictionary[key], 3);
}
这篇关于如何通过词典和变化值循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文