How does ToList() on an IEnumerable work?
.net, c#, ienumerable, list
Solution
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.
Problem
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`.