根据指定的键从集合中创建键值对集合
2017-08-13 20:20
148 查看
假如有一个对象的集合,想转换成键值对,然后通过键去访问值,通常这个对象有一个唯一标识"Id"
可以根据这个students集合去创建一个键值对
键就是Id属性,值就是Student对象。有些时候值没必要存Student对象,只需要Name就可以了
需要注意的两个地方:
1、Id不能有重复
2、键值对不能通过索引0取第一条数据 dic[0] 这样写是不对的
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] 这样写是不对的
相关文章推荐
- 用java的IO流和集合创建一个存储指定文件列表示例
- linq 根据指定条件返回集合中不重复的元素
- 链表的基本操作(创建,查找指定位置元素,删除指定元素,插入,倒置,去重,求集合的差,分别交换结点与交换结点值实现的冒泡排序,将两个有序链表合并成一个有序链表)c语言实现
- 根据泛型的类型,创建泛型类型的集合对象
- 根据指定类型创建数组
- 获取集合、数组后要判断为空的必要性以及根据构造器创建对象后不是null的证实
- 获取集合、数组后要判断为空的必要性以及根据构造器创建对象后不是null的证实
- 根据指定类名创建实例(Java的反射机制)
- 键值对集合Dictionary<K,V>根据索引提取数据
- 根据包名,在指定空间中创建对象
- 创建曲线偏置根据指定矢量
- 根据ResultSetMetaData对象动态创建pojo或其集合(JDBC)
- 根据字符串创建指定的实例
- 根据指定经纬度创建地图并且定位
- 根据包名,在指定空间中创建对象
- 根据指定的编码格式返回请求的参数集合
- CSS+HTML实例集合三,用户自定义创建表格并删除指定行、列,对表格中的数据进行排序,radio单选摁扭之调查问卷、之选择题
- JavaScript根据指定路径创建对象
- 根据sheet1指定行数往sheet2中写数据
- 根据字段表 自动创建 表SQL