ToList() 使用IEnumerable<T>并将其转换为 List<T>,那么 ToDictionary()也是相似的。大多数状况ToDictionary()是一个很是方便的方法,将查询的结果(或任何 IEnumerable<T>)转换成一个Dictionary<TKey,TValue>。 关键是您须要定义T如何分别转换TKey和TValue。c#
若是说咱们有超级大的产品列表,但愿把它放在一个Dictionary<int, product>,这样咱们能够根据ID获得最快的查找时间。 你可能会这样作:单元测试
var results = new Dictionary<int, Product>(); foreach (var product in products) { results.Add(product.Id, product); }
和它看起来像一个很好的代码,可是咱们能够轻松地使用LINQ而无需手写一大堆逻辑:测试
var results = products.ToDictionary(product => product.Id);
它构造一个Dictionary<int, Product> ,Key是产品的Id属性,Value是产品自己。 这是最简单的形式ToDictionary(),你只须要指定一个key选择器。 若是你想要不一样的东西做为你的value? 例如若是你不在意整个Product,,你只是但愿可以转换ID到Name? 咱们能够这样作:code
var results = products.ToDictionary(product => product.Id, product => product.Name);
这将建立一个 Key为Id,Value为Name 的Dictionary<int, string>,。由此来看这个扩展方法有不少的方式来处理IEnumerable<T> 集合或查询结果来生成一个dictionary。blog
注:还有一个Lookup<TKey, TValue>类和ToLookup()扩展方法,能够以相似的方式作到这一点。 他们不是彻底相同的解决方案(Dictionary和Lookup接口不一样,他们的没有找到索引时行为也是不一样的)。索引
所以,在咱们的Product 示例中,假设咱们想建立一个Dictionary<string, List<Product>> ,Key是分类,Value是全部产品的列表。 在之前你可能自实现本身的循环:接口
1 // create your dictionary to hold results 2 var results = new Dictionary<string, List<Product>>(); 3 4 // iterate through products 5 foreach (var product in products) 6 { 7 List<Product> subList; 8 9 // if the category is not in there, create new list and add to dictionary 10 if (!results.TryGetValue(product.Category, out subList)) 11 { 12 subList = new List<Product>(); 13 results.Add(product.Category, subList); 14 } 15 16 // add the product to the new (or existing) sub-list 17 subList.Add(product); 18 }
但代码应该更简单! 任何新人看着这段代码可能须要去详细分析才能彻底理解它,这给维护带来了困难开发
幸运的是,对咱们来讲,咱们能够利用LINQ扩展方法GroupBy()提早助力ToDictionary()和ToList():string
// one line of code! var results = products.GroupBy(product => product.Category) .ToDictionary(group => group.Key, group => group.ToList());
GroupBy()是用Key和IEnumerable建立一个IGrouping的LINQ表达式查询语句。 因此一旦咱们使用GroupBy() ,全部咱们要作的就是把这些groups转换成dictionary,因此咱们的key选择器 (group => group.Key) 分组字段(Category),使它的成为dictionary的key和Value择器((group => group.ToList()) 项目,并将它转换成一个List<Product>做为咱们dictionary的Value!产品
这样更容易读和写,单元测试的代码也更少了! 我知道不少人会说lamda表达式更难以阅读,但他们是c#语言的一部分,高级开发人员也必须理解。我认为你会发现当你愈来愈多的使用他们后,代码能被更好的理解和比之前更具可读性。