How to iterate through Dictionary and change values?

后端 未结 8 442
灰色年华
灰色年华 2020-12-02 17:52
Dictionary myDict = new Dictionary();
//...
foreach (KeyValuePair kvp in myDict)
 {
     kvp.Value = Math.Round(kvp.Value,          


        
相关标签:
8条回答
  • 2020-12-02 18:45

    Loop through the keys in the dictionary, not the KeyValuePairs.

    Dictionary<string, double> myDict = new Dictionary<string, double>();
    //...
    foreach (string key in myDict.Keys)
    {
        myDict[key] = Math.Round(myDict[key], 3);
    }
    
    0 讨论(0)
  • 2020-12-02 18:48

    While iterating over the dictionary directly is not possible because you get an exception (like Ron already said), you don't need to use a temp list to solve the problem.

    Instead use not the foreach, but a for loop to iterate through the dictionary and change the values with indexed access:

    Dictionary<string, double> myDict = new Dictionary<string,double>();
    //...    
    for(int i = 0; i < myDict.Count; i++) {
        myDict[myDict.ElementAt(i).Key] = Math.Round(myDict.ElementAt(i).Value, 3);
    }
    
    0 讨论(0)
提交回复
热议问题