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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2026 CODEPRJ.COM