DEV Community

yashaswi
yashaswi

Posted on

[Post 2]LINQ -IEnumerator

[Post-2] [LINQ] IEnumerator

Now that we have talked about *“Enumerable” .Lets talk about *“Enumerator”.

Enumerators are those that make a data structure Enumerable.

I.e. Enumerators help traverse or iterate an Enumerable. IEnumerable and IEnumerator implement the “Iterator Pattern”.

**Iterator** is a behavioral design pattern that lets you traverse elements of a collection without exposing its underlying representation (list, stack, tree, etc.).

Making it simple Iterator pattern asks us to separate the underlying data collection and the functionality to traverse it.

Below are the IEnumerator and IEnumerable interfaces. IEnumerable exposes a method which returns an IEnumerator. IEnumerator provides following methods and properties.

bool MoveNext(): Moves the pointer to next item in the collection and returns true. If the pointer is at the end of collection it returns false.

**object Current: **This property provides the current values of the item the pointer is located at.

**void Reset(): **Although not extensively used or is part of *Iterator pattern *UML diagram, this method sets the pointer to the initial value of the collection.

Look at the below example where different data structures return their Enumerators using which the these are iterated.


If you notice, in the above code we are iterating different data structures using same method “Enumerate”. If you get back to the *Iterator Pattern *definition, irrespective of the characteristics or internal implementation of the data structure we are able to iterate them uniformly.

Although it is not a common practice to use the enumerator for iterating a data structure. [Instead we would use the foreach *loop directly.] Understanding this particular concept helps in understanding **LINQ*.

In the next post lets look into **Yield **and how IEnumerable and Yield are linked together.

Thanks, please subscribe to the publication for more interesting posts.

[References]

Iterator Pattern : *https://www.youtube.com/watch?v=uNTNEfwYXhI*

Top comments (0)