[英]How does ToList() on an IEnumerable work?
How does the extension method ToList()
work? 扩展方法ToList()
工作? Say I have an IEnumerable
of 10000 items. 说我有一个IEnumerable
10000项。 Will ToList()
create a new List
and iterate over the IEnumerable
of 10000 items and then return me a List
or does .NET do it in some other way? 将ToList()
创建一个新的List
并遍历IEnumerable
的10000个项目,然后返回一个List
或者.NET以其他方式执行吗?
This MSDN link talks about immediate execution of a DB query. 此MSDN链接讨论了数据库查询的立即执行。 My question is only about converting IEnumerable
to a List
. 我的问题只是将IEnumerable
转换为List
。
It doesn't necessarily iterate, although that's the "worst case" scenario. 它不一定会迭代,尽管这是“最坏情况”的情况。 Basically it calls new List<T>(source)
, but that has some tricks up its sleeve: if the source implements ICollection<T>
, the constructor can call ICollection<T>.CopyTo()
to copy the complete data into an array. 基本上它调用了new List<T>(source)
,但它有一些技巧:如果源实现ICollection<T>
,构造函数可以调用ICollection<T>.CopyTo()
将完整数据复制到数组中。 This may well be implemented more efficiently than single-stepping iteration. 与单步迭代相比,这可以更有效地实现。 Likewise in the ICollection<T>
case, the new list knows the final size to start with, so it won't need to keep expanding its internal buffers. 同样在ICollection<T>
情况下,新列表知道要开始的最终大小,因此它不需要继续扩展其内部缓冲区。
For a few more details, see my Edulinq ToList()
blog post . 有关更多详细信息,请参阅我的Edulinq ToList()
博客文章 。
The .ToList
extension method calls the List<T>
constructor passing it the IEnumerable<T>
. .ToList
扩展方法调用List<T>
构造函数,将IEnumerable<T>
传递给它。 This constructor will iterate over the IEnumerable<T>
and copy the elemtns of the IEnumerable<T>
in the same order they are returned. 此构造将迭代IEnumerable<T>
并复制的elemtns IEnumerable<T>
在它们返回的顺序相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.