Home
VB.NET
GetEnumerator Function (List)
Updated Jul 14, 2024
Dot Net Perls
GetEnumerator. Some collections in .NET, such as the List, have a GetEnumerator function that can be used to access elements in a unified way. We can use GetEnumerator to get an Enumerator.
For most programs, we will want to just the List directory, and loop over its elements in a For-Each loop. But occasionally a more abstracted approach (like IEnumerator) is helpful.
List
For
Example. This program calls the GetEnumerator Function on a List of Integers. It shows how we can use GetEnumerator and then pass the Enumerator as an IEnumerator instance.
Part 1 We create an empty List Of Integers, and then in 3 subsequent calls to Add, we add 3 elements to the List.
Part 2 We call GetEnumerator. This returns a typed Enumerator, and we can pass this object as an IEnumerator (it implements IEnumerator).
Interface
Part 3 Once we have an IEnumerator reference, we can call MoveNext and Current to iterate over the elements in the underlying enumerator.
Module Module1 Sub Main() ' Part 1: create List of Integer values. Dim values As List(Of Integer) = New List(Of Integer) values.Add(1) values.Add(5) values.Add(9) ' Part 2: call GetEnumerator and pass to a Sub that receives IEnumerator. Dim e As List(Of Integer).Enumerator = values.GetEnumerator() Write(e) End Sub Sub Write(e As IEnumerator(Of Integer)) ' Part 3: Use IEnumerator interface to display all elements. While e.MoveNext() Dim value = e.Current Console.WriteLine(value) End While End Sub End Module
1 5 9
Consider a program that enumerates elements and performs some complex logic on the elements. The underlying collection (like List or array) may not matter as much.
And with GetEnumerator and IEnumerator, we can write the complex loop-based logic once, and reuse it for any underlying collection. All that is needed is GetEnumerator.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jul 14, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen