快捷搜索:

[译文]c# /.Net 技巧: ToDictionary() and ToList()

有两个简单好用的LINQ扩展方法 ToDictionary() 和ToList(),你可能知道或不知道,但是它的的确确可以简化查询转化为集合的任务:

简介: LINQ和延迟执行

据你所认识的LINQ,你可能会不知道这些查询表达式在幕后做了些什么。 让我们说说今天我们示例的目的,我们有一些POCO类(POCO代表传统CLR对象,指的是一个类,它只有非常少的功能,这一概念源自Java POJO)。

1 // just a simple product POCO class. 2 public class Product 3 { 4 public string Name { get; set; } 5 public int Id { get; set; } 6 public string Category { get; set; } 7 }

非常简单的类,对吗? 我不是说程序需要如此简单,只是专注于LINQ本身,而且我们不一定要真正查询。 所以,在我们的程序中我们可以构建一个简单的例子,这些对象的集合的示例如下:

1 var products = new List<Product> 2 { 3 new Product { Name = "CD Player", Id = 1, Category = "Electronics" }, 4 new Product { Name = "DVD Player", Id = 2, Category = "Electronics" }, 5 new Product { Name = "Blu-Ray Player", Id = 3, Category = "Electronics" }, 6 new Product { Name = "LCD TV", Id = 4, Category = "Electronics" }, 7 new Product { Name = "Wiper Fluid", Id = 5, Category = "Automotive" }, 8 new Product { Name = "LED TV", Id = 6, Category = "Electronics" }, 9 new Product { Name = "VHS Player", Id = 7, Category = "Electronics" }, 10 new Product { Name = "Mud Flaps", Id = 8, Category = "Automotive" }, 11 new Product { Name = "Plasma TV", Id = 9, Category = "Electronics" }, 12 new Product { Name = "Washer", Id = 10, Category = "Appliances" }, 13 new Product { Name = "Stove", Id = 11, Category = "Electronics" }, 14 new Product { Name = "Dryer", Id = 12, Category = "Electronics" }, 15 new Product { Name = "Cup Holder", Id = 13, Category = "Automotive" }, 16 };

就是说,有这些产品的对象集合,你需要查询它们。 例如,我们可以这样得到一个所有产品实例的类别为“Electronics”的集合:

1 var electronicProducts = products.Where(p => p.Category == "Electronics");

许多扩展方法(包括Where() )的查询结果是创建一个迭代器通过移动列表来执行查询。 因此,此时的electronicProducts不是List<Product>,只是IEnumerable<Product>,它会在您使用这个列表时动态求值. 这就是LINQ中强大的延迟执行,在你需要结果前,都不会对表达式求值。 此时我们可以去查询electronicProducts,这样我们就可以得到结果列表!

让我看一下下面的结果是什么:

1 // select all electronics, there are 7 of them 2 IEnumerable<Product> electronicProducts = products.Where(p => p.Category == "Electronics"); 3 4 // now clear the original list we queried 5 products.Clear(); 6 7 // now iterate over those electronics we selected first 8 Console.WriteLine(electronicProducts.Count());

您可能还会对下面的文章感兴趣: