假如有一个对象的集合,想转换成键值对,然后通过键去访问值,通常这个对象有一个唯一标识"Id"
public class Student { public int Id { get; set; } public string Name { get; set; } public string Phone { get; set; } } IEnumerable<Student> students = new List<Student>() { new Student(){Id = 1, Name = "关羽", Phone = "13648965479"}, new Student(){Id = 2, Name = "张飞", Phone = "13648965479"}, new Student(){Id = 3, Name = "赵云", Phone = "13648965479"}, new Student(){Id = 4, Name = "马超", Phone = "13648965479"}, new Student(){Id = 5, Name = "黄忠", Phone = "13648965479"} };
可以根据这个students集合去创建一个键值对
Dictionary<int, Student> dic = students.ToDictionary(u => u.Id);
键就是Id属性,值就是Student对象。有些时候值没必要存Student对象,只需要Name就可以了
Dictionary<int, string> dic = students.ToDictionary(u => u.Id, u => u.Name);
需要注意的两个地方:
1、Id不能有重复
2、键值对不能通过索引0取第一条数据 dic[0] 这样写是不对的
时间: 2024-11-01 18:47:40