C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: In the Display Sub, we use the For-Each loop to enumerate the elements within the IEnumerable collection argument.
For Each, ForSo: We can act upon a List and an array with the same code, by using the IEnumerable interface implemented by both types.
VB.NET program that uses IEnumerable
Module Module1
Sub Main()
' Create a List.
Dim list1 As List(Of String) = New List(Of String)
list1.Add("one")
list1.Add("two")
list1.Add("three")
' Create a String array.
Dim array1(2) As String
array1(0) = "ONE"
array1(1) = "TWO"
array1(2) = "THREE"
' Pass both to the Display sub.
Display(list1)
Display(array1)
End Sub
Sub Display(ByVal argument As IEnumerable(Of String))
' Loop over IEnumerable.
For Each value As String In argument
Console.WriteLine("Value: {0}", value)
Next
Console.WriteLine()
End Sub
End Module
Output
Value: one
Value: two
Value: three
Value: ONE
Value: TWO
Value: THREE
Here: We employ the ToList extension. This converts any IEnumerable type into a List. The element type remains the same.
ToListCast: In this example, we implicitly cast the array into an IEnumerable reference. This step is not required.
Note: We use this statement to show how the array is an IEnumerable instance, as well as an array.
VB.NET program that uses IEnumerable, Extension
Module Module1
Sub Main()
' An array.
' ... This implements IEnumerable.
Dim array1() As String = {"cat", "dog", "mouse"}
' Cast the array to IEnumerable reference.
Dim reference1 As IEnumerable(Of String) = array1
' Use an extension method on IEnumerable.
Dim list1 As List(Of String) = reference1.ToList()
' Display result.
Console.WriteLine(list1.Count)
End Sub
End Module
Output
3
Tip: In most programs, we will not need to implement IEnumerable ourselves. This is possible, but is not covered here.
Instead: A thorough understanding of how to use IEnumerable on built-in types, including Lists and arrays, often has more benefit.