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

24

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

例如:

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个回答

40

你可以在字典上使用 foreach 循环,这将为每次迭代提供一个 DictionaryEntry 对象。你可以从该对象访问 KeyValue 属性。

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

谢谢,我正需要这个答案,通过迭代“this.Context.Parameters”来返回DictionaryEntry集合。 - Bravo
使用ListDictionary非常完美! - JillAndMe
十年后,有几件事情需要注意:首先,value.Key和value.Value返回为对象类型,对于许多用例,即使持有类型是“StringDictionary”,也可能需要进行强制转换。各种答案中的示例隐式地实现了转换或使用常规字典。其次,“StringDictionary”将键返回为小写,而常规“Dictionary”则不会。MS Doco指出了这一点,但可能会被忽视。 - Rob Von Nesselrode

14
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);
}

当然,我会把它改成Dictionary<string,string>。 - user160677

4

应该只需要一个:

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

  // Process key/value pair here
}

或者我误解了你的问题?

你理解得没错!每个人的答案都完美地运作着。 - user160677

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);

问题是关于使用StringDictionary,而不是Dictionary<string,string>。 - Rafael Rivera

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

1

你可以直接枚举字典本身。它应该返回一系列的DictionaryEntry实例。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接