Enumerable.Range
Sometimes we want to act upon an IEnumerable
and the values are already known—like the values are 1 through 10, or they repeat. We can invoke Enumerable.Range
for a range.
And with Repeat, we can get a collection of repeating values—think 10, 10, and then another 10. Empty()
gives us an IEnumerable
of no elements—this can be useful in some places too.
Here we invoke Enumerable.Range
. We call this Function with 2 arguments, and it returns the specified range of values as an IEnumerable
of the specified type.
Enumerable.Range
is the starting number. This can be positive or negative. Here we use 6.Enumerable.Range
is the number (count) of values we want to have in the resulting array.Module Module1 Sub Main() Dim range As IEnumerable(Of Integer) = Enumerable.Range(6, 4) ' Display the range. For Each number As Integer In range Console.WriteLine("RANGE ELEMENT: {0}", number) Next End Sub End ModuleRANGE ELEMENT: 6 RANGE ELEMENT: 7 RANGE ELEMENT: 8 RANGE ELEMENT: 9
Here we call the Enumerable.Repeat
Function. Like Range, this method receives 2 arguments—and it also returns an IEnumerable
of the specified type, which we can loop over.
Module Module1 Sub Main() ' Repeat the number 3 four times. For Each number As Integer In Enumerable.Repeat(3, 4) Console.WriteLine("REPEAT: {0}", number) Next End Sub End ModuleREPEAT: 3 REPEAT: 3 REPEAT: 3 REPEAT: 3
This returns an IEnumerable
collection of 0 elements. In some methods that may require an IEnumerable
, but we have no elements, we can pass this as an argument.
Module Module1 Sub Main() Dim empty As IEnumerable(Of String) = Enumerable.Empty(Of String)() ' Count the empty collection. Console.WriteLine("EMPTY COUNT: {0}", empty.Count()) End Sub End ModuleEMPTY COUNT: 0
Range, Repeat and Empty are helpful in many programs. Instead of writing methods to generate ranges (for example) we can invoke Range()
and avoid all that extra code.