Ser*_*gey 68 .net dictionary c#-3.0
Dictionary<string,double> myDict = new Dictionary();
//...
foreach (KeyValuePair<string,double> kvp in myDict)
{
kvp.Value = Math.Round(kvp.Value, 3);
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:"无法将属性或索引器'System.Collections.Generic.KeyValuePair.Value'分配给它 - 它是只读的."
如何迭代myDict
并更改值?
Jus*_* R. 100
根据MSDN:
foreach语句是枚举器的包装器,它只允许从集合中读取,而不是写入它.
用这个:
var dictionary = new Dictionary<string, double>();
// TODO Populate your dictionary here
var keys = new List<string>(dictionary.Keys);
foreach (string key in keys)
{
dictionary[key] = Math.Round(dictionary[key], 3);
}
Run Code Online (Sandbox Code Playgroud)
小智 34
对于懒惰的程序员:
Dictionary<string, double> dictionary = new Dictionary<string, double>();
foreach (var key in dictionary.Keys.ToList())
{
dictionary[key] = Math.Round(dictionary[key], 3);
}
Run Code Online (Sandbox Code Playgroud)
在迭代时不应该更改字典,否则会出现异常.
首先将键值对复制到临时列表,然后遍历此临时列表,然后更改字典:
Dictionary<string, double> myDict = new Dictionary<string, double>();
// a few values to play with
myDict["a"] = 2.200001;
myDict["b"] = 77777.3333;
myDict["c"] = 2.3459999999;
// prepare the temp list
List<KeyValuePair<string, double>> list = new List<KeyValuePair<string, double>>(myDict);
// iterate through the list and then change the dictionary object
foreach (KeyValuePair<string, double> kvp in list)
{
myDict[kvp.Key] = Math.Round(kvp.Value, 3);
}
// print the output
foreach (var pair in myDict)
{
Console.WriteLine(pair.Key + " = " + pair.Value);
}
// uncomment if needed
// Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
输出(在我的机器上):
a = 2.2
b = 77777.333
c = 2.346
注意:就性能而言,此解决方案比当前发布的解决方案稍好一些,因为该值已经使用密钥分配,并且无需再次从字典对象中获取它.
已经有一段时间了,但也许有人对此感兴趣:
yourDict = yourDict.ToDictionary(kv => kv.Key, kv => Math.Round(kv.Value, 3))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
68128 次 |
最近记录: |