Jack
Jack

Reputation: 7567

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.

Upvotes: 8

Views: 3144

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1504172

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.

Upvotes: 22

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

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.

Upvotes: 3

Related Questions