kevin marchand
kevin marchand

Reputation: 635

IEnumerator<T> Implementation

I have a this code

public class SomeClass<T>: IEnumerable<T>
{
    public List<SomeClass<T>> MyList = new List<SomeClass<T>>();

    public IEnumerator<T> GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

How can I Extract a IEnumerator from MyList ?

Thanks StackoverFlower....

Upvotes: 3

Views: 3286

Answers (5)

Ben
Ben

Reputation: 113

As an add on to the accepted answer, if you received the message

MyNamespace.MyClass<T>' does not implement interface
  member 'System.Collections.IEnumerable.GetEnumerator()'.
  'WindowsFormsApplication1.SomeClass<T>.GetEnumerator()' cannot implement
  'System.Collections.IEnumerable.GetEnumerator()' because it does not have
  the matching return type of 'System.Collections.IEnumerator'.

You need to implement the additional GetEnumerator() method:

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}

IEnumerable<T> implements IEnumerable so both forms of GetEnumerator() must be implemented.

Upvotes: 0

kemiller2002
kemiller2002

Reputation: 115538

This:

public List<SomeClass<T>> MyList = new List<SomeClass<T>>();

Needs to be this:

public List<T> MyList = new List<T>();

then, this should work:

public IEnumerator<T> Getenumerator ()
{
  foreach (var item in MyList){
     yield return item;}
}

You can't have a

List<SomeClass<T>>

that you pull the enumerator for, because you have specified in the interface that the enumerator will return an enumerable item of <T>. You can also change IEnumerable<T> to be

IEnumerable<SomeClass<T>>

and change the Enumerator to be

public IEnumerator<SomeClass<T>> Getenumerator ()
{
  foreach (var item in MyList){
     yield return item;}
}

Upvotes: 7

G-Wiz
G-Wiz

Reputation: 7426

Assuming there is a way to get an object T out of an object SomeClass,

public IEnumerator<T> GetEnumerator()
{
    return MyList.Select(ml => ml.GetT() /* operation to get T */).GetEnumerator();
}

Upvotes: 1

mandel
mandel

Reputation: 2947

Kevins answer is the correct and is lazy (even better). If you use Trodek response the following exception will be throw:

Cannot implicitly convert type `System.Collections.Generic.List<SomeClass<T>>.Enumerator' to `System.Collections.Generic.IEnumerator<T>'(CS0029)

Nevertheless I want to add a comment. When you use yield return a state machine is generated which will be returning the different values. If you are going to use nested data structures (trees for example) using yield return will be allocating far more memory because a different state machine will be created in every sub structure.

Well, those are my two cents!

Upvotes: 1

Tordek
Tordek

Reputation: 10882

The trivial option would be return MyList.GetEnumerator().

Upvotes: 1

Related Questions