linq学习笔记:将List<T> 转换为 Dictionary<T Key,T Value>
2013-08-29 10:29
781 查看
运用Linq,将List<T> 转换为 Dictionary<T Key,T Value>
即:[b]List<T> To[b]Dictionary<T Key,T Value>[/b][/b]
废话不说,看代码:
示例代码:按照性别分类
实际运行结果:
轻松利用linQ
即:[b]List<T> To[b]Dictionary<T Key,T Value>[/b][/b]
废话不说,看代码:
示例代码:按照性别分类
class Program { public class Student { public string Name { get; set; } public int Age { get; set; } public int Sex { get; set; } } static void Main(string[] args) { List<Student> lstStudent = new List<Student>(); lstStudent.Add(new Student { Name = "A1", Age = 17, Sex = 0 }); lstStudent.Add(new Student { Name = "A2", Age = 19, Sex = 1 }); lstStudent.Add(new Student { Name = "A3", Age = 17, Sex = 1 }); lstStudent.Add(new Student { Name = "A4", Age = 19, Sex = 0 }); lstStudent.Add(new Student { Name = "A5", Age = 18, Sex = 1 }); lstStudent.Add(new Student { Name = "A6", Age = 18, Sex = 0 }); lstStudent.Add(new Student { Name = "A7", Age = 18, Sex = 1 }); lstStudent.Add(new Student { Name = "A8", Age = 19, Sex = 0 }); lstStudent.Add(new Student { Name = "A9", Age = 19, Sex = 0 }); var dicStudent = lstStudent.GroupBy(p => p.Sex).ToDictionary(p => p.Key, p => p.ToList()); foreach (var dic in dicStudent) { Console.WriteLine("Key:{0}", dic.Key); foreach (var stu in dic.Value) { Console.WriteLine("Name:{0},Age:{1}", stu.Name, stu.Sex.ToString()); } } Console.ReadKey(); } }
实际运行结果:
Key:0 Name:A1,Age:0 Name:A4,Age:0 Name:A6,Age:0 Name:A8,Age:0 Name:A9,Age:0 Key:1 Name:A2,Age:1 Name:A3,Age:1 Name:A5,Age:1 Name:A7,Age:1
轻松利用linQ
相关文章推荐
- .net学习笔记----有序集合SortedList、SortedList<TKey,TValue>、SortedDictionary<TKey,TValue>
- C#学习笔记--ArrayList?List<T>?Dictionary
- Dictionary、List<KeyValuePair<i>>的组合使用
- 将正则表达式处理的内容转换到Dictionary<key, value>中
- c#学习笔记对IEnumerable<T>,IDictionary<Tkey,TValue>,ICollection<T>,IList<T>的总结
- C# Dictionary<TKey, TValue>的学习
- .NET源码中的SortedDictionary<TKey, TValue>和SortedList<TKey, TValue>
- .Net学习 第2季05 C#面向对象 ArrayList Hashtable List<> Dictionary<>
- Dictionary<TKey, TValue> 类
- 我的Android进阶之旅------>android如何将List<NameValuePair>请求参数列表转换为json格式
- C#基础第四天-作业答案-Hashtable-list<KeyValuePair>泛型实现名片
- c#扩展方法奇思妙用基础篇五:Dictionary<TKey, TValue> 扩展
- Guava学习笔记-简化List分组成Map<String,List>的实现
- c# 扩展方法奇思妙用基础篇五:Dictionary<TKey, TValue> 扩展
- .Net 中HashTable,HashMap 和 Dictionary<key,value> 和List<T>和DataTable的比较
- 取出List<Map<String,Object>>里面Map的key:value值
- C# - IOrderedDictionary<TKey, TValue> Implementation
- SortedList<TKey,TValue> 和 SortedDictionary<TKey,TValue>
- C#学习常用类(3000)---ConcurrentDictionary<TKey,TValue>类
- Linq 学习笔记<转帖>