sprocket12
sprocket12

Reputation: 5488

How to simplify generation of number range using linq?

If I have a number x which can change, say its now 25... how do I do the below in a simpler way?

colQty.DataSource = new List<Int16> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 };

Upvotes: 2

Views: 167

Answers (3)

Bonny Bonev
Bonny Bonev

Reputation: 131

var list = new List<int>();

for(var i = 1; i <= x; i++){ list.Add(i);}

colQty.DataSource = list;

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273189

Something like

 var range = Enumerable.Range(start: 1, count: x).ToList();

And you could use ToList<Int16>() but I wouldn't.

Upvotes: 7

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

Use this:

var numbers = Enumerable.Range(1, 25);

This will create an IEnumerable<int> with the numbers 1 to 25. If you need a List<int> instead, add .ToList() after Range:

var numbers = Enumerable.Range(1, 25).ToList();

Upvotes: 3

Related Questions