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--)
{
}
-
possible duplicate: What is the best way to iterate over a Dictionary in C#?publicgk– publicgk2013年03月06日 07:19:56 +00:00Commented Mar 6, 2013 at 7:19
-
3or this ;) stackoverflow.com/questions/1070766/…Belial09– Belial092013年03月06日 07:20:18 +00:00Commented Mar 6, 2013 at 7:20
-
1@Belial09 In the question asked in the link you posted, it doesn't seem the keys are modified; just the values.joce– joce2013年04月11日 21:04:34 +00:00Commented Apr 11, 2013 at 21:04
4 Answers 4
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;
}
5 Comments
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.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());
Comments
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());
Comments
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();
}