using a for loop to iterate through a dictionary

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

I generally use a foreach loop to iterate through Dictionary.

Dictionary dictSummary = new Dictionary();
<         


        
相关标签:
3条回答
  • 2020-12-16 10:02

    You don't need to use .ToArray() or .ElementAt(). It is as simple as accessing the dictionary with the key:

    dictSummary.Keys.ToList().ForEach(k => dictSummary[k] = dictSummary[k].Trim());
    
    0 讨论(0)
  • 2020-12-16 10:07

    KeyValuePair<TKey, TValue> 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());
    
    0 讨论(0)
  • 2020-12-16 10:11

    what about this?

    for (int i = dictSummary.Count - 1; i >= 0; i--) {
      var item = dictSummary.ElementAt(i);
      var itemKey = item.Key;
      var itemValue = item.Value;
    }
    
    0 讨论(0)
提交回复
热议问题