45

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--)
{
}
Theodor Zoulias
45.7k8 gold badges110 silver badges154 bronze badges
asked Mar 6, 2013 at 7:18
3

4 Answers 4

65

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;
}
answered Mar 6, 2013 at 7:27
Sign up to request clarification or add additional context in comments.

5 Comments

While it is possible to use such code I'd not recommend it. Enumerable.ElementAt is not really best way to access elements in a dictionary... Your code is likely O(n^2) since Dictionary does not allow access to elements by position.
Why are you iterating from the end to the beginning? Don't tell me, it's because of performance reasons...
@AlexeiLevenkov ...Thanks. I didn't know about this. just searched the issue and it looks like a huge drawback. Thanks again.
@DHN...well, i've just copied it from the ques
This isn't a good use case of reverse iteration. But the proper use case is if you plan to remove items. That way a removal doesn't affect your iteration/count.
30

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());
answered Mar 6, 2013 at 7:21

Comments

6

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());
answered Oct 27, 2015 at 15:05

Comments

0

An alternative to the solution from @AbdulAhad

var keys = dictSummary.Keys.ToList();
for (int i = 0; i < keys.Count; i++)
{
 var key = keys[i];
 dictSummary[key] = dictSummary[key].Trim();
}
answered Oct 7, 2024 at 15:14

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.