views:

1331

answers:

4

I need a list of integers from 1 to x where x is set by the user. I could build it with a for loop eg assuming x is an integer set previously:

List<int> iList = new List<int>();
for (int i = 1; i <= x; i++)
{
    iList.Add(i);
}

This seems dumb, surely there's a more elegant way to do this, something like the PHP range method

+6  A: 

LINQ to the rescue:

// Adding value to existing list
var list = new List<int>();
list.AddRange(Enumerable.Range(1, x));

// Creating new list
var list = Enumerable.Range(1, x).ToList();

See Generation Operators on LINQ 101

aku
+11  A: 

If your using .Net 3.5, Enumerable.Range is what you need.

Generates a sequence of integral numbers within a specified range.

John
This will return an IEnumerable<int>, not a List<int>, so like aku noted, you'll want to call .ToList() on the Enumerable.Range(x,y) call.
Daniel Jennings
Thanks for pointing that out. :)
John
its generally better to use IEnumerable<> wherever possible for fullest flexibility. especially if this list doesnt change it most likely neednt be a generic List<T>
Simon_Weaver
A: 

LINQ to the rescue:

List list = from i in Sequence.Range(1, x) select i;

Daren Thomas
Same mistake as in my post :) Replace Sequence with Enumerable
aku
+3  A: 
Samuel Jack
The other answers are more likely what the questioner was looking for, but I voted up here because I like the resulting syntax. How much more readable can you get than "1.To(10)"?
Jay Bazuzi