LINQ: Defining a List of Integers
Posted
Fri, Jul 3 2009 9:39
by
Deborah Kurata
Defining a list of integers in your code involves lots of tedious typing.
In VB, you can’t do this:
'Dim numberList As new List(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9}
So you have to either add numbers to the list manually, or create an array, which still involves lots of tedious typing:
Dim numberList() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9}
With .NET 3.5, you can instead use the Range method of the Enumerable class that is part of the System.Linq namespace.
In VB:
Dim numberList2 As List(Of Integer) = Enumerable.Range(1, 9).ToList
In C#:
List<int> numberList2 = Enumerable.Range(1, 9).ToList();
The first parameter of the Range method defines the first integer of the sequence. The second parameter defines the number of items in the sequence. So Range(0,9) provides 9 integers from 0 through 8.
Enjoy!