C# - StringDictionary - 如何使用单个循环获取键和值?

时间:2009-08-25 10:07:06

标签: c# collections

我正在使用StringDictionary集合来收集键值对。

E.g:

StringDictionary KeyValue = new StringDictionary();
KeyValue.Add("A", "Load");
KeyValue.Add("C", "Save");

在检索过程中,我必须形成两个foreach来获取密钥和值(即)

foreach(string key in KeyValue.Values)
{
   ...
}

foreach(string key in KeyValue.Keys)
{
   ...
}

有没有办法让这对在单foreach

6 个答案:

答案 0 :(得分:37)

您可以在字典上执行foreach循环,这将在每次迭代中为您提供DictionaryEntry。您可以从该对象访问KeyValue属性。

foreach (DictionaryEntry value in KeyValue)
{
    // use value.Key and value.Value
}

答案 1 :(得分:13)

StringDictionary可以作为DictionaryEntry项重复:

foreach (DictionaryEntry item in KeyValue) {
   Console.WriteLine("{0} = {1}", item.Key, item.Value);
}

我建议你改用最近的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);
}

答案 2 :(得分:3)

你已经有很多答案了。但是根据你想做的事情,你可以使用一些LINQ。

假设您要获取使用CTRL键的快捷方式列表。你可以这样做:

var dict = new Dictionary<string, string>();
dict.Add("Ctrl+A", "Select all");
dict.Add("...", "...");

var ctrlShortcuts =
    dict
        .Where(x => x.Key.StartsWith("Ctrl+"))
        .ToDictionary(x => x.Key, x => x.Value);

答案 3 :(得分:2)

一个就足够了:

foreach (string key in KeyValue.Keys)
{
  string value = KeyValue[key];

  // Process key/value pair here
}

或者我误解了你的问题?

答案 4 :(得分:1)

foreach(DictionaryEntry entry in KeyValue)
{
    // ...
}

答案 5 :(得分:1)

您可以简单地枚举字典本身。它应该返回一系列DictionaryEntry实例。

更好的选择是使用Dictionary<string, string>