Thursday, October 12, 2006

[.NET 2.0] Foreach-ing Arrays with Iterator & Generics

Prior to the .NET 2.0, we have to use for statement to loop each of the element in the array. C# 2.0 offers you another one - Iterator, a familar word that in the Design Pattern, a method that can be used to enumerate through collection of values such as array and return each of the element in turn. For instance,

Code

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];
}
Output :
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: