在介绍tolist()的时候我先个大家介绍一下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 }; 17 18 // select all electronics, there are 7 of them 19 IEnumerable<Product> electronicProducts = products.Where(p => p.Category == "Electronics"); 20 21 // now clear the original list we queried 22 products.Clear(); 23 24 // now iterate over those electronics we selected first 25 Console.WriteLine(electronicProducts.Count());
许多扩展方法(包括Where() )的查询结果是创建一个迭代器通过移动列表来执行查询。 因此,此时的electronicProducts不是List<Product>,只是IEnumerable<Product>,它会在您使用这个列表时动态求值. 这就是LINQ中强大的延迟执行,在你需要结果前,都不会对表达式求值。 此时我们可以去查询electronicProducts,这样我们就可以得到结果列表!
但是如果我们换一种写法这个值就会是7:
1 var electronicProducts = products.Where(p => p.Category == "Electronics").ToList();
现在, List<T>代替 electronicProducts 作为IEnumerable<T> 动态执行的原始集合,这将是另一个新的集合,修改不会影响原来的集合。
当然,这有优点也有缺点。 通常,如果你只是要遍历的结果和过程,你不需要(也不想)将它存储在一个单独的列表,这只会浪费内存,后来还需要垃圾收集。 然而,如果你想保存子集,并将它分配给另一个类,ToList()是非常方便的,你不需要担心改变原来的集合。
ToList()内存消耗
tolist和lazy load是对立的 ,tolist是直接将linq语句的执行结果放于list集合中,直接将结果存放在内存中,所以数据量大的时候,使用tolist要谨慎。
时间: 2024-11-06 07:16:56