2009-05-13 6 views

答えて

5
Dictionary<KeyType, ValueType> myDictionary = . . . 


foreach(KeyValuePair<KeyType, ValueType> item in myDictionary) 
{ 
    Console.WriteLine("Key={0}: Value={1}", item.Key, item.Value); 
} 
+0

。 。 。それは汎用的な辞書だとしたら、ごめんなさい –

+0

+1シンプルでクリア! –

1

下図のようにあなたは、foreachループを使用することができます私は今までに与えられた解決策があなたのためのトリックを行うだろうと思うが):

// set up the dictionary 
Dictionary<string, string> dictionary = new Dictionary<string, string>(); 
dictionary.Add("A key", "Some value"); 
dictionary.Add("Another key", "Some other value"); 

// loop over it 
Dictionary<string, string>.Enumerator enumerator = dictionary.GetEnumerator(); 
while (enumerator.MoveNext()) 
{ 
    Console.WriteLine(enumerator.Current.Key + "=" + enumerator.Current.Value); 
} 
+1

おっと、少し遅れています... –

1

をそれともは、Visual Studio 2008から作業する場合、あなたは可能性があります:

+0

KeyValuePair (ここで、myDictionaryはIDictionary です)の項目のタイプの指定。 – Richard

1

私のお気に入りのアプローチは、このいずれかになります。

Dictionary<string, string> dict = new Dictionary<string, string>(); 
dict.Add("key1", "value2"); 
dict.Add("key2", "value"); 
foreach (KeyValuePair<string, string> item in dict) 
    Console.WriteLine(item.Key + "=" + item.Value); 
+0

"Foreach"アプローチは素敵でシンプルで、おそらくコンパイラの最適化によって何らかの方法で高速化されていますが、 "While"ソリューションは、ループトラフを終了するための読みやすい方法を醜い "exit for "は、" foreach "をネストした場合の問題です。だから "中"の返事は今日の私の投票を持っている:) – tomasofen

関連する問題