I generally use a foreach loop to iterate through Dictionary.
Dictionary<string, string> dictSummary = new Dictionary<string, string>();
In this case I want to trim the entries of white space and the foreach loop does however not allow for this.
foreach (var kvp in dictSummary) { kvp.Value = kvp.Value.Trim(); }
How can I do this with a for loop?
for (int i = dictSummary.Count - 1; i >= 0; i--) { }
You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example. You can iterate keys by using the dictionary object directly in a for loop.
When you iterate through dictionaries using the for .. in .. -syntax, it always iterates over the keys (the values are accessible using dictionary[key] ). To iterate over key-value pairs, use the following: for k,v in dict.
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; }
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With