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

 

posted @ 2016-03-11 15:38  齐_大圣  阅读(10587)  评论(0编辑  收藏  举报