Strong Coders Community

Where the extreme coders hang out.
Welcome to Strong Coders Community Sign in | Join | Help Messenger
in Search

Cool trick with iterators.

Last post 12-11-2006, 12:23 PM by JamesCurran . 0 replies.
Sort Posts: Previous Next
  •  12-11-2006, 12:23 PM 1409
    • JamesCurran is not online. Last active: Feb 11, 2007, 11:18 AM JamesCurran
    • Top 10 Contributor
      Male
    • Joined on 11-01-2006
    • Bloomfield, NJ, USA
    • Posts 82
    • Points 1,015
    • StrongCoders

    Cool trick with iterators.

    Things seem a bit slow here, so I thought I share a cool trick I just stumpled upon using C# iterators.

    Actually, I'm not sure why it took me so long to come up with it, as it's basically the same thing I've been doing with C++ iterators for about 10 years.

    Let's say we want to fill a List with the numbers from 1 to 100.  There's no simple way. You'd have to write a loop:

    List myList = new List();
    for(int i = 1; i<=100; ++i)
          myList.Add(i);

    But, Lists can be initialized from a IEnumerator.  The intention was to allow copying one list into another, but as long as its an IEnumerable, we can work with it:

    List myList(Filler.IntFill(1, 100));

    WIth the Filler class defined as:

    public class Filler
    {
        static public IEnumerable IntFill(int start, int end, int step)
        {
            for (int i = start; i <= end; i += step)
            {
                yield return i;
            }
        }

        static public IEnumerable IntFill(int start, int end)
        {
            return IntFill(start, end, 1);
        }
    }

    The trick is to recognize that while iterators are intended to step through a containter, as long as they return a value, it doesn't matter where that value came from.

    Also, I would have really liked to have made that a generic class, except there's no way say that generic type T understands +=.  (we gotta get MSFT to fix that.....)


    Truth,
    James
    • Post Points: 5
    • Alert the moderators

Powered by Community Server (Commercial Edition), by Telligent Systems