42

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--)
{
}
Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
Arianule
  • 8,811
  • 45
  • 116
  • 174
  • possible duplicate: [What is the best way to iterate over a Dictionary in C#?](http://stackoverflow.com/questions/141088/what-is-the-best-way-to-iterate-over-a-dictionary-in-c) – publicgk Mar 06 '13 at 07:19
  • 3
    or this ;) http://stackoverflow.com/questions/1070766/editing-dictionary-values-in-a-foreach-loop – Belial09 Mar 06 '13 at 07:20
  • 1
    @Belial09 In the question asked in the link you posted, it doesn't seem the keys are modified; just the values. – joce Apr 11 '13 at 21:04

3 Answers3

63

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;
}
Abdul Ahad
  • 2,187
  • 4
  • 24
  • 39
  • 6
    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. – Alexei Levenkov Mar 06 '13 at 07:34
  • 1
    Why are you iterating from the end to the beginning? Don't tell me, it's because of performance reasons... – DHN Mar 06 '13 at 07:50
  • @AlexeiLevenkov ...Thanks. I didn't know about this. just searched the issue and it looks like a huge drawback. Thanks again. – Abdul Ahad Mar 06 '13 at 07:52
  • 2
    @DHN...well, i've just copied it from the ques – Abdul Ahad Mar 06 '13 at 07:55
  • 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. – Suamere Jun 18 '21 at 17:35
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());
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
7

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());
Community
  • 1
  • 1
Moslem Ben Dhaou
  • 6,897
  • 8
  • 62
  • 93