Deborah's Developer MindScape

         Tips and Techniques for Web and .NET developers.

July 3, 2009

LINQ: Defining a List of Integers

Filed under: C#,LINQ,VB.NET @ 11:39 am

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.


RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2020 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs