C# Dictionary几种遍历方式
class Program { static void Main(string[] args) { Dictionary<string, string> myDictionary = new Dictionary<string, string>(); myDictionary.Add("No1", "Zhang San"); myDictionary.Add("No2", "Li Si"); myDictionary.Add("No3", "Wang Wu"); Console.WriteLine("Dictionary遍历方式:"); Console.WriteLine("方法1:"); //3.0版本以上 foreach (var v in myDictionary) { Console.WriteLine("Key:" + v.Key + ";Value:" + v.Value); } Console.WriteLine("方法2:"); foreach (KeyValuePair<string, string> kvp in myDictionary) { Console.WriteLine("Key:" + kvp.Key + ";Value:" + kvp.Value); } Console.WriteLine("方法3:"); foreach (string key in myDictionary.Keys) { Console.WriteLine("Key:" + key + ";Value:" + myDictionary[key]); } Console.WriteLine("方法4:"); foreach (string value in myDictionary.Values) { Console.WriteLine("Value:"+value); } Console.Read(); } }