扩展方法之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

运行效果:

原文地址:https://www.cnblogs.com/527289276qq/p/4444308.html