Code
Output :
string[] aryNames = {"Alvin","Westley","Howard"};
foreach(string str in IterateMe(aryNames))
Response.Write(str + " ");
private IEnumerable IterateMe(string[] str)
{
int iLength = str.Length;
for(int index=0;index < iLength;index++)
yield return str[index];
}
Alvin Westley Howard
Your Iterator method has to return either IEnumerable or IEnumerator type to the caller function, which in turn contains the element value of current iteration. Make it more usable with generic,
Code:
string[] aryNames = {"Alvin","Westley","Howard"};
int[] iValues = {1,2,15,4,6,9};
foreach(string str in IterateMe< string >(aryNames,true))
Response.Write(str + " ");
foreach(int value in IterateMe< int >(iValues,true))
Response.Write(value + " ");
private IEnumerable IterateMe< T >(T[] str, bool sorting)
{
if(sorting && !typeof(T).Name.Equals("Object"))
Array.Sort(str);
int iLength = str.Length;
for(int index=0;index < iLength;index++)
yield return str[index];
}
Output:
Alvin Howard Westley
1 2 3 6 9 15
No comments:
Post a Comment