您的位置:首页 > 其它

根据指定的键从集合中创建键值对集合

2017-08-13 20:20 148 查看
假如有一个对象的集合,想转换成键值对,然后通过键去访问值,通常这个对象有一个唯一标识"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] 这样写是不对的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: