Tuesday, June 5, 2012

Iterating an enumerable in C#


Suppose you have an enumerable and you need to iterate it in order to do something. I know that's not a very common need but it may happen. It happened to me and I came up with this solution.


using System.Collections.Generic;

namespace Events
{
    public enum MenuItemEvent
    {
        Click,
        Select
    }

    public class MenuItemEvents : List<MenuItemEvent>
    {
        public MenuItemEvents()
        {
            var item = 0;
            while (true)
            {
                if (((MenuItemEvent) item).ToString() == item.ToString())
                    break;

                Add((MenuItemEvent) item);
                item++;
            }
        }
    }
}

Now you can foreach every element of the enum.

No comments:

Post a Comment