An easy way to populate a list with integers in .NET.

Possible duplicate:
Filling a list of integers in .NET

Is there an easier or more elegant way to initialize a list of integers in C # besides 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 should contain a large number of values. Would a cycle be a more practical solution?

Thank,

CC

+63
list c # linq
Feb 07 2018-11-11T00:
source share
2 answers

Since you are already using C #, you can use the Enumerable.Range() method:

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

The first parameter is the integer to start with, and the second parameter is the number of consecutive integers.

+138
Feb 07 2018-11-11T00:
source share

If your initialization list is simple, like a sequential sequence of values ​​from from to end , you can simply say

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

If your initialization list is something more complex that can be determined by matching 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(); 

will generate the first ten primes, assuming Prime is Func<int, int> , which takes int n and returns n th prime.

+31
Feb 07 2018-11-11T00:
source share



All Articles