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-2025 CODEPRJ.COM