使用for循环通过字典来遍历 [英] using a for loop to iterate through a dictionary
问题描述
我一般使用foreach循环通过字典来迭代
词典<字符串,字符串> dictSummary =新词典<字符串,字符串>();
在这种情况下,我要修剪的空白和foreach循环也不过不允许的条目这一点。
的foreach(在dictSummary VAR KVP)
{
kvp.Value = kvp.Value。修剪();
}
我怎么能循环做到这一点了?
的for(int i = dictSummary.Count - 1; I> = 0;我 - )
{
$} b $ b
KeyValuePair< TKEY的,TValue>
不允许设置值
,这是不可改变的。
您将不得不做这样的:
的foreach(在dictSummary.ToArray VAR KVP())
dictSummary [KVP的.key] = kvp.Value.Trim();
这里最重要的部分是的ToArray
。这将词典复制到一个数组,所以改变的foreach里面的字典将不会抛出出现InvalidOperationException
。
另一种方法是使用LINQ的 ToDictionary
方法:
dictSummary = dictSummary。 ToDictionary(X => x.Key中,x => x.Value.Trim());
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循环通过字典来遍历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!