简体   繁体   中英

How does ToList() on an IEnumerable work?

How does the extension method ToList() work? Say I have an IEnumerable of 10000 items. 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?

This MSDN link talks about immediate execution of a DB query. My question is only about converting IEnumerable to a 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. 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.

For a few more details, see my Edulinq ToList() blog post .

The .ToList extension method calls the List<T> constructor passing it the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM