Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

obtain generic enumerator from an array

In C#, how does one obtain a generic enumerator from a given array?

In the code below, MyArray is an array of MyType objects. I'd like to obtain MyIEnumerator in the fashion shown, but it seems that I obtain an empty enumerator (although I've confirmed that MyArray.Length > 0).

MyType[] MyArray = ... ; IEnumerator<MyType> MyIEnumerator = MyArray.GetEnumerator() as IEnumerator<MyType>; 
like image 282
JaysonFix Avatar asked Aug 13 '09 15:08

JaysonFix


1 Answers

Works on 2.0+:

((IEnumerable<MyType>)myArray).GetEnumerator() 

Works on 3.5+ (fancy LINQy, a bit less efficient):

myArray.Cast<MyType>().GetEnumerator()   // returns IEnumerator<MyType> 
like image 57
mmx Avatar answered Sep 16 '22 20:09

mmx