IEnumerable
An IEnumerable
collection contains elements. We use the For-Each
loop in VB.NET to loop over these elements. Lists and arrays implement this interface
.
We can use Extensions, such as ToList
, on an IEnumerable
type. Query expressions, part of LINQ, can be done with IEnumerables
as well.
We can use the IEnumerable
type to reference types like lists and arrays. This can help programs become smaller and easier to maintain.
List
and a String
array. These types both implement IEnumerable
.Sub
—it receives an IEnumerable
(Of String
) argument.Sub
, we use the For-Each
loop to enumerate the elements within the IEnumerable
collection argument.List
and an array with the same code, by using the IEnumerable
interface
implemented by both types.Module Module1 Sub Main() ' Step 1: create a List and String array. Dim list1 As List(Of String) = New List(Of String) list1.Add("one") list1.Add("two") list1.Add("three") Dim array1(2) As String array1(0) = "ONE" array1(1) = "TWO" array1(2) = "THREE" ' Step 2: pass both to the Display sub. Display(list1) Display(array1) End Sub Sub Display(ByVal argument As IEnumerable(Of String)) ' Step 3: loop over IEnumerable. For Each value As String In argument Console.WriteLine("Value: {0}", value) Next Console.WriteLine() End Sub End ModuleValue: one Value: two Value: three Value: ONE Value: TWO Value: THREE
IEnumerable
has other uses. Many Extension methods that act upon IEnumerable
are implemented. These are available in all VB.NET programs based on recent .NET Frameworks.
ToList
extension. This converts any IEnumerable
type into a List
. The element type remains the same.IEnumerable
reference. This step is not required.IEnumerable
instance, as well as an array.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 Module3
The IEnumerable
interface
is a critical abstraction in .NET. Many Functions are built upon this abstraction. Even the For-Each
loop, a core construct, directly uses IEnumerable
.
IEnumerable
ourselves. This is possible, but is not covered here.IEnumerable
on built-in types, including Lists and arrays, often has more benefit.We explored the IEnumerable
type in VB.NET. This interface
is needed for the For-Each
loop. It can be used to act upon arrays, Lists and many other collections with a unified code path.