I generally use a foreach loop to iterate through Dictionary.
Dictionary dictSummary = new Dictionary();
<
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());
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());
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;
}