using a for loop to iterate through a dictionary

后端 未结 3 1648
陌清茗
陌清茗 2020-12-16 09:53

I generally use a foreach loop to iterate through Dictionary.

Dictionary dictSummary = new Dictionary();
<         


        
3条回答
  •  借酒劲吻你
    2020-12-16 10:07

    KeyValuePair doesn't allow you to set the Value, it is immutable.

    You will have to do it like this:

    foreach(var kvp in dictSummary.ToArray())
        dictSummary[kvp.Key] = kvp.Value.Trim();
    

    The important part here is the ToArray. That will copy the Dictionary into an array, so changing the dictionary inside the foreach will not throw an InvalidOperationException.

    An alternative approach would use LINQ's ToDictionary method:

    dictSummary = dictSummary.ToDictionary(x => x.Key, x => x.Value.Trim());
    

提交回复
热议问题