2009-08-25 63 views
18

我正在使用StringDictionary集合來收集關鍵值對。C# - 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一對?

回答

33

你可以在字典上做一個foreach循環,它會在每次迭代中給你一個DictionaryEntry。您可以訪問該對象的KeyValue屬性。

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

謝謝,我需要這個答案,迭代通過'this.Context.Parameters'返回DictionaryEntry集合。 – Bravo 2012-08-27 06:44:14

2

每個人都應該已經足夠了:

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

    // Process key/value pair here 
} 

還是我誤解你的問題?

+0

你明白的是對的!每個人的回答都很完美 – user160677 2009-08-25 10:15:45

+0

有人低估了我的回答,becaaaaauuuse ...? – 2015-11-20 16:51:33

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

您可以簡單地列舉字典本身。它應該返回一系列DictionaryEntry實例。

更好的選擇是使用Dictionary<string, string>

+0

謝謝Mark.I會跟進。 – user160677 2009-08-25 10:17:30

10

的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); 
} 
+0

當然。我會將其中一個改爲Dictionary user160677 2009-08-25 10:23:44

+0

這個應該被接受的答案。 – 2017-09-26 14:44:13

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

酷!這一個也很有用。 – user160677 2009-08-25 10:19:37

+0

問題是關於使用StringDictionary,而不是Dictionary 。 – 2011-01-10 10:31:48

相關問題