Monday, 2 April 2012

Beginning.Net : Working with IEnumerable/IEnumerator interfaces

IEnumerable is an interface implemented by the System.Collecetion type in .NET that provides the iterator pattern.

IEnumerator allows you to iterate over List or Array and process each element one by one.

Here are example :
In this example we show how we can use IEnumerator to iterate.

Here we declare one List(Of String) object and insert some records in that.
        Dim SportsList As New Generic.List(Of String)
        SportsList.Add("Cricket")
        SportsList.Add("Hockey")
        SportsList.Add("Soccer")
        SportsList.Add("BaseBall")
        SportsList.Add("Tennis")

Now We can iterate through normal FOR loop
        For Each strSport As String In SportsList
            Response.Write(strSport)
            Response.Write("</br>")
        Next

Output :
Cricket
Hockey
Soccer
BaseBall
Tennis

Now We can iterate through IEnumerator interface object
        Dim enumerator As IEnumerator = SportsList.GetEnumerator
        While enumerator.MoveNext
            Dim strSport As String = Convert.ToString(enumerator.Current)
            Response.Write(strSport)
            Response.Write("</br>")
        End While

Output :
Cricket
Hockey
Soccer
BaseBall
Tennis

No comments:

Post a Comment