How to iterate through Dictionary and change values?

后端 未结 8 463
灰色年华
灰色年华 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:35

    According to MSDN:

    The foreach statement is a wrapper around the enumerator, which allows only reading from the collection, not writing to it.

    Use this:

    var dictionary = new Dictionary();
    // TODO Populate your dictionary here
    var keys = new List(dictionary.Keys);
    foreach (string key in keys)
    {
       dictionary[key] = Math.Round(dictionary[key], 3);
    }
    

提交回复
热议问题