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--)
{
}
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());
那这个呢?
for (int i = dictSummary.Count - 1; i >= 0; i--) {
var item = dictSummary.ElementAt(i);
var itemKey = item.Key;
var itemValue = item.Value;
}
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());
链接地址: http://www.djcxy.com/p/30390.html
上一篇: 在C#中迭代字典
下一篇: 使用for循环遍历字典