Implement IEnumerable<T> in C# on linked list built from scratch
To add to Bradley's answer, note that methods returning IEnumerator<T>
also support the yield
keyword:
public class LinkedList<T> : IEnumerable<T>
{
...
// this will automagically create the
// appropriate class for you
public IEnumerator<T> GetEnumerator()
{
Node<T> current = First;
while (current != null)
{
yield return current.Value;
current = current.Next;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
// this will invoke the public generic
// version, so there is no recursion
return this.GetEnumerator();
}
}
You should, however, remove Current
and Reset()
from the parent class, they don't belong there. And your GetLastNode()
method has two duplicate variables, you can remove one of them.
Since you have created a custom collection, you won't be able to just use an existing IEnumerator
implementation. You'll need to create one:
public class LinkedListEnumerator<T> : IEnumerator<T>
{
public LinkedListEnumerator(LinkedList<T> collection)
{
}
...
}
I'm passing the collection to be enumerated into the constructor. Other ways could work but that seemed the easiest way to get it there. Now your IEnumerable<T>
implementation is:
public IEnumerator<T> GetEnumerator()
{
return new LinkedListEnumerator<T>(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new LinkedListEnumerator<T>(this);
}
Actual IEnumerator
implementation left as an exercise.