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 implementsICollection<T>, the constructor can callICollection<T>.CopyTo()to copy the complete data into an array. This may well be implemented more efficiently than single-stepping iteration. Likewise in theICollection<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.