Easier way to populate a list with integers in .NET

You can take advantage of the Enumerable.Range() method:

var numberList = Enumerable.Range(1, 10).ToList();

The first parameter is the integer to start at and the second parameter is how many sequential integers to include.


If your initialization list is as simple as a consecutive sequence of values from from to end, you can just say

var numbers = Enumerable.Range(from, end - from + 1)
                        .ToList();

If your initialization list is something a little more intricate that can be defined by a mapping f from int to int, you can say

var numbers = Enumerable.Range(from, end - from + 1)
                        .Select(n => f(n))
                        .ToList();

For example:

var primes = Enumerable.Range(1, 10)
                       .Select(n => Prime(n))
                       .ToList();

would generate the first ten primes assuming that Prime is a Func<int, int> that takes an int n and returns the nth prime.

Tags:

C#

.Net

Linq

List