Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a built-in way to convert IEnumerator to IEnumerable

Tags:

c#

.net

linq

Is there a built-in way to convert IEnumerator<T> to IEnumerable<T>?

like image 814
Sam Saffron Avatar asked Jun 22 '09 21:06

Sam Saffron


People also ask

What is the difference between IEnumerator and IEnumerable?

An IEnumerator is a thing that can enumerate: it has the Current property and the MoveNext and Reset methods (which in . NET code you probably won't call explicitly, though you could). An IEnumerable is a thing that can be enumerated...which simply means that it has a GetEnumerator method that returns an IEnumerator .

What is the use of IEnumerator?

Here is the documentation on IEnumerator . They are used to get the values of lists, where the length is not necessarily known ahead of time (even though it could be). The word comes from enumerate , which means "to count off or name one by one".

What is GetEnumerator C#?

The C# GetEnumerator() method is used to convert string object into char enumerator. It returns instance of CharEnumerator. So, you can iterate string through loop.

What is IEnumerator interface?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. This works for readonly access to a collection that implements that IEnumerable can be used with a foreach statement. IEnumerator has two methods MoveNext and Reset. It also has a property called Current.


1 Answers

The easiest way of converting I can think of is via the yield statement

public static IEnumerable<T> ToIEnumerable<T>(this IEnumerator<T> enumerator) {   while ( enumerator.MoveNext() ) {     yield return enumerator.Current;   } } 

compared to the list version this has the advantage of not enumerating the entire list before returning an IEnumerable. using the yield statement you'd only iterate over the items you need, whereas using the list version, you'd first iterate over all items in the list and then all the items you need.

for a little more fun you could change it to

public static IEnumerable<K> Select<K,T>(this IEnumerator<T> e,                                           Func<K,T> selector) {       while ( e.MoveNext() ) {         yield return selector(e.Current);       }     } 

you'd then be able to use linq on your enumerator like:

IEnumerator<T> enumerator; var someList = from item in enumerator                select new classThatTakesTInConstructor(item); 
like image 128
Rune FS Avatar answered Oct 19 '22 00:10

Rune FS