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.
Range example. 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.
Argument 1 The first argument to Enumerable.Range is the starting number. This can be positive or negative. Here we use 6.
Argument 2 The second argument to 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
Repeat. 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.
Argument 1 This is the value we want to have repeated. In this example, we like the number 3, and want many copies of it.
Argument 2 This is the repetition count. So by passing the value 4 as the second argument, we get 4 repeated numbers.
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
Empty. 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
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.