Hongseok Yoon
Hongseok Yoon

Reputation: 3318

I'd like to iterate object using foreach statement

There's a kind of list container(eg. MyList what I cannot modify) but declared only GetCount() and At() methods.

I'd like to use foreach statement for MyList, so I wrote extension method like bellow.

public static class MyListHelper
{
    public static IEnumerable<MyListItemType> GetEnumerator(this MyList list)
    {
        for (int i = 0; i < list.GetCount(); ++i )
        {
            yield return list.At(i);
        }
    }
}

But if I code 'foreach (MyListItemType i in list)...', compiler vomits 'MyList does not contain a piblic definition for GetEnumerator'.

I can invoke GetEnumerator() method directly and works okay.

What should I do more for that?

Upvotes: 2

Views: 108

Answers (3)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

If you can't edit the code of the MyList (non-static) class directly, you probably have to make an extension method ToIEnumerable or similar. Maybe something like:

public static class MyListExtensions
{
  public static IEnumerable<MyListItemType> ToIEnumerable(this MyList list)
  {
    return new Wrapper(list)
  }

  private class Wrapper : IEnumerable<MyListItemType>
  {
    readonly MyList list;

    public Wrapper(MyList list)
    {
      this.list = list;
    }

    public IEnumerator<MyListItemType> GetEnumerator() 
    { 
      for (int i = 0; i < list.GetCount(); ++i )
      { 
        yield return list.At(i); 
      } 
    }

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

Upvotes: 3

frogwang
frogwang

Reputation: 64

Your MyList need to implement interface IEnumerable

public class MyList:IEnumerable<MyListItemType>
{
    public IEnumerable<MyListItemType> GetEnumerator()
    {
        ...
    }
}

Upvotes: 1

akton
akton

Reputation: 14386

Change MyList to implement the IEnumerable or IEnumerable<T> interface. This includes GetEnumerator.

Upvotes: 2

Related Questions