How to iterate through Dictionary and change values?

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

    You shouldn't change the dictionary while iterating it, otherwise you get an exception.

    So first copy the key-value pairs to a temp list and then iterate through this temp list and then change your dictionary:

    Dictionary myDict = new Dictionary();
    
    // a few values to play with
    myDict["a"] = 2.200001;
    myDict["b"] = 77777.3333;
    myDict["c"] = 2.3459999999;
    
    // prepare the temp list
    List> list = new List>(myDict);
    
    // iterate through the list and then change the dictionary object
    foreach (KeyValuePair 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();
    

    output (on my machine):

    a = 2.2
    b = 77777.333
    c = 2.346

    Note: in terms of performance, this solution is a bit better than currently posted solutions, since the value is already assigned with the key, and there's no need to fetch it again from the dictionary object.

提交回复
热议问题