我有一个快速的问题.有没有通过的方式来容易循环System.Collections.Generic.Dictionary
通过for
在C#中的语句?
提前致谢.
Phi*_*ert 11
你可以使用foreach:
Dictionary<string,string> dictionary = new Dictionary<string,string>();
// ...
foreach (KeyValuePair<string,string> kv in dictionary)
{
string key = kv.Key;
string value = kv.Value;
}
Run Code Online (Sandbox Code Playgroud)
不合理,没有.你可以使用Linq扩展ElementAt
:
for (int i = 0; i < dictionary.Keys.Count; i++)
{
Console.WriteLine(dictionary.ElementAt(i).Value);
}
Run Code Online (Sandbox Code Playgroud)
......但我真的没有看到这一点.只需使用常规foreach
方法.如果由于某种原因需要在迭代时跟踪索引,则可以"在侧面"执行此操作:
int index = 0;
foreach (var item in dictionary)
{
Console.WriteLine(string.Format("[{0}] - {1}", index, item.Value));
// increment the index
index++;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16828 次 |
最近记录: |