利用KeyValuePair遍歷Dictionary

下面是用KeyValuePair遍歷Dictionary的例子:        

 

   public void test()
        {
            Dictionary<string,modelTest> tDictonart=new Dictionary<string,modelTest>();
            modelTest t1=new modelTest(25,"張三");
            modelTest t2=new  modelTest(24,"李四");
            modelTest t3=new modelTest(25,"王五");
            tDictonart.Add("張三",t1);
            tDictonart.Add("李四",t2);
            tDictonart.Add("王五",t3);
            foreach(KeyValuePair<string,modelTest> tKeyValuePair in tDictonart)
            {
              MessageBox.Show(tKeyValuePair.Value.Name+":"+ tKeyValuePair.Value.Age+";");
            }

            foreach(KeyValuePair<string,modelTest> tKeyValuePair in tDictonart)
            {
            if(tKeyValuePair.Value.Name=="張三")
            {
            MessageBox.Show("張三:"+tKeyValuePair.Value.Age);
            }
            }

        }

        public class modelTest
        {
            public int Age {get;set; }
            public string Name { get; set; }
            public modelTest(int age,string name)
            {
                Age=age;
                Name=name;
            }
        }

 

發佈了88 篇原創文章 · 獲贊 16 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章