views:

634

answers:

4

Hi,

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....

+2  A: 

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

Tordek
Are you sure about that> I hav enot tired the code, but from my understanding you will be returning an IEnumerator<SomeClasss<T>> instead of IEnumerator<T>
mandel
Just checked, you will get the following error:Cannot implicitly convert type `System.Collections.Generic.List<SomeClass<T>>.Enumerator' to `System.Collections.Generic.IEnumerator<T>'(CS0029)
mandel
Is the object meant to hold a list of instances of its class? Don't you mean `public List<T>`?
Tordek
+6  A: 

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;}
}
Kevin
Wouldn't item still be of type SomeClass<T>?
Dennis Palmer
I'm getting: 'WindowsFormsApplication1.SomeClass<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'.
jasonh
'yield' is a widely overlooked construct.. props for mentioning it :-)
CodeMonkey
Widely overlooked?
sixlettervariables
+1  A: 

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!

mandel
+1  A: 

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();
}
gWiz