Pass your IEnumerable<item> array before calling GetEnumerator() , and you get a generic IEnumerator . For instance:
string[] names = { "Jon", "Marc" }; IEnumerator<string> enumerable = ((IEnumerable<string>)names).GetEnumerator();
It may still be a little slower than listing the array directly using foreach (which the C # compiler does differently), but at least you won't have anything in the way.
EDIT:
Well, you said that your other attempt used an indexer. You can try this approach, although I do not think it will be faster:
public IEnumerable<Item> Items { get { foreach (Item x in items) { yield return x; } } }
An alternative would be to try to avoid using a two-dimensional array for starters. Is this an absolute requirement? How often do you repeat a single array after creating it? It might be worth spending some time creating to make iteration cheaper.
EDIT: Another suggestion, which is slightly off the wall ... instead of passing the iterator back to the caller, why not make the caller say what to do with each element using a delegate?
public void ForEachItem(Action action) { foreach (Item item in items) { action(item); } }
Downsides:
- You are responsible for calling a delegate with every access.
- It is hard to break out of the loop (except throw an exception). There are different ways to approach this, but let me cross this bridge when we get to it.
- Developers who are not familiar with delegates can get a little confused.
source share