Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a for loop to iterate through a dictionary

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--) { } 
like image 892
Arianule Avatar asked Mar 06 '13 07:03

Arianule


People also ask

Can you iterate through a dictionary with a for loop?

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.

How do I iterate through a dictionary item?

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.

Does looping over a dictionary using a for statement always iterate over its values?

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.


2 Answers

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; } 
like image 112
Abdul Ahad Avatar answered Sep 23 '22 23:09

Abdul Ahad


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()); 
like image 20
Daniel Hilgarth Avatar answered Sep 26 '22 23:09

Daniel Hilgarth