悟生慧

 

C#利用KeyValuePair实现Dictionary的遍历方法

public class Class1
        {
            public string Name;
            public int Age;

            public Class1(string name, int age)
            {
                this.Name = name;
                this.Age = age;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Dictionary<string, Class1> cl = new Dictionary<string, Class1>();
            Class1 s1 = new Class1("张三", 25);
            Class1 s2 = new Class1("李四", 26);
            Class1 s3 = new Class1("家六", 27);

            cl.Add(s1.Name, s1);
            cl.Add(s2.Name, s2);
            cl.Add(s3.Name, s3);

            foreach (KeyValuePair<string, Class1> a in cl)
            {
                MessageBox.Show(a.Value.Age.ToString() + "  " + a.Value.Name.ToString());
            }
            foreach (KeyValuePair<string, Class1> a in cl)
            {
                if (a.Key == s1.Name)
                    MessageBox.Show(a.Value.Age.ToString() + "  " + a.Value.Name.ToString());
            }

            //本文来自: IT知道网(http://www.itwis.com) 详细出处参考:http://www.itwis.com/html/net/c/20110318/10072.html
        }

posted on 2011-12-16 14:53  悟生慧  阅读(8150)  评论(4编辑  收藏  举报

导航