如何通过词典和变化值循环?词典

2023-09-02 01:46:33 作者:爱上她我会发光

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);
}