C# 使用 for 循环遍历字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15241257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using a for loop to iterate through a dictionary
提问by Arianule
I generally use a foreach loop to iterate through Dictionary.
我通常使用 foreach 循环来遍历 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 循环不允许这样做。
foreach (var kvp in dictSummary)
{
kvp.Value = kvp.Value.Trim();
}
How can I do this with a for loop?
我怎样才能用 for 循环做到这一点?
for (int i = dictSummary.Count - 1; i >= 0; i--)
{
}
采纳答案by Daniel Hilgarth
KeyValuePair<TKey, TValue>
doesn't allow you to set the Value
, it is immutable.
KeyValuePair<TKey, TValue>
不允许您设置Value
,它是不可变的。
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
.
这里的重要部分是ToArray
. 这会将 Dictionary 复制到一个数组中,因此更改 foreach 中的字典不会抛出InvalidOperationException
.
An alternative approach would use LINQ's ToDictionary
method:
另一种方法是使用 LINQ 的ToDictionary
方法:
dictSummary = dictSummary.ToDictionary(x => x.Key, x => x.Value.Trim());
回答by Abdul Ahad
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;
}
回答by Moslem Ben Dhaou
You don't need to use .ToArray()
or .ElementAt()
. It is as simple as accessing the dictionary with the key:
您不需要使用.ToArray()
或.ElementAt()
。它就像使用键访问字典一样简单:
dictSummary.Keys.ToList().ForEach(k => dictSummary[k] = dictSummary[k].Trim());