如何迭代字典和更改值? [英] How to iterate through Dictionary and change values?

查看:159
本文介绍了如何迭代字典和更改值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆