扩展方法之ToDictionary()

Person类:

public class Person
    {
        public int Id { set; get; }
        public string WorkNo { set; get; }
        public string Name { set; get; }

        public override string ToString()
        {
            return string.Format("{0}:{1}",WorkNo,Name);
        }
    }
View Code

Main函数:

static void Main(string[] args)
        {
            List<Person> lst = new List<Person>()
            {
                new Person{Id=1,Name="张三",WorkNo="1001"},
                new Person{Id=2,Name="李四",WorkNo="1086"},
                new Person{Id=3,Name="王五",WorkNo="1099"},
                new Person{Id=4,Name="赵六",WorkNo="1032"},
                new Person{Id=5,Name="孙七",WorkNo="1045"},
            };

            Dictionary<int, Person> dic = lst.ToDictionary(c => c.Id, c => c);

            foreach (int Id in dic.Keys)
            {
                Console.WriteLine("键:{0},   值: {1}", Id, dic[Id]);
            }

            Console.ReadKey();
        }
View Code

运行效果:

posted @ 2015-04-21 14:46  秋刀鱼No1  阅读(520)  评论(0编辑  收藏  举报