Easier way to populate a list with integers in .NET

C#.NetLinqList

C# Problem Overview


> Possible Duplicate:
> Populating a list of integers in .NET

Is there a simpler or more elegant way of initializing a list of integers in C# other than this?

List<int> numberList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

or

for(int i = 1; i <= 10; i++)
{
    numberList.Add(i);
}

It just doesn't seem very practical - especially if the list was to contain a large number of values. Would a loop be a more practical solution?

Thanks,

CC

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThe Coding CowboyView Question on Stackoverflow
Solution 1 - C#Rion WilliamsView Answer on Stackoverflow
Solution 2 - C#jasonView Answer on Stackoverflow