简体   繁体   中英

Why is LINQ ToList not used here?

I see the following code:

using(var iterator = source.GetEnumerator()) {...}

Where source is a IEnumerable<T> .

What is the advantage of doing the above versus converting source into a List<T> and then iterating over it?

Converting it to a list will iterate the enumerable once and copy all the references (or even values for value types) into a new List<> . Then, you would iterate over the list. That means you would iterate twice.

Using the IEnumerable<> as a source for enumeration iterates over the sequence only once.

Why someone decided to do the iteration manually using the enumerator instead of leaving the details to a foreach is unclear from the small scope you posted.

  1. Converting to a List<T> would require additional memory and CPU cycles to perform the conversion not to mention you'd be iterating over the data twice.

  2. There's no need to convert to a List<T> before iterating. foreach can iterate over anything that implements IEnumerable<T> .

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