我正在使用StringDictionary集合来收集Key Value Pairs.
例如:
StringDictionary KeyValue = new StringDictionary();
KeyValue.Add("A", "Load");
KeyValue.Add("C", "Save");
Run Code Online (Sandbox Code Playgroud)
在检索过程中,我必须形成两个foreach来获取键和值(即)
foreach(string key in KeyValue.Values)
{
...
}
foreach(string key in KeyValue.Keys)
{
...
}
Run Code Online (Sandbox Code Playgroud)
有没有办法让这对搭配单身foreach?
Fre*_*örk 37
你可以foreach在字典上做一个循环,它会DictionaryEntry在每次迭代中给你一个循环.您可以从该对象访问Key和Value属性.
foreach (DictionaryEntry value in KeyValue)
{
// use value.Key and value.Value
}
Run Code Online (Sandbox Code Playgroud)
Guf*_*ffa 13
StringDictionary可以作为DictionaryEntry项重复:
foreach (DictionaryEntry item in KeyValue) {
Console.WriteLine("{0} = {1}", item.Key, item.Value);
}
Run Code Online (Sandbox Code Playgroud)
我建议您使用更新的Dictionary<string,string>类:
Dictionary<string, string> KeyValue = new Dictionary<string, string>();
KeyValue.Add("A", "Load");
KeyValue.Add("C", "Save");
foreach (KeyValuePair<string, string> item in KeyValue) {
Console.WriteLine("{0} = {1}", item.Key, item.Value);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55104 次 |
| 最近记录: |