码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-08-13 20:46:48      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:hone   键值   phone   cti   nts   ict   color   不能   属性   

假如有一个对象的集合,想转换成键值对,然后通过键去访问值,通常这个对象有一个唯一标识"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] 这样写是不对的



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

标签:hone   键值   phone   cti   nts   ict   color   不能   属性   

原文地址:http://www.cnblogs.com/bidianqing/p/7354619.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!