An elegant way to create a list <int> just with (int) from and (int) before

I need an elegant way to create a new List<int>

one with integers only.

Example:

var from = 2;
var to = 5;

      

I want it:

List<int> { 2, 3, 4, 5 };

      

Of course, I could do it in a simple scheme:

var results = new List<int>();
for (var i = from; i <= to; i++)
{
     results.Add(i);
}

      

But I want a more efficient or elegant way.

+3


source to share


3 answers


Of course use Enumerable.Range

:

var results = Enumerable.Range(2, 4).ToList();

      



Note that 4

here refers to the number of integers that should be included in the list of results. Therefore, to create the range specified by the from

and variables to

, use:

var results = Enumerable.Range(from, to - from + 1).ToList();

      

+7


source


var results = Enumerable.Range(from,to-from+1);

      



+2


source


use Enumerable.Range

var results = Enumerable.Range(from, to - from + 1); // +1 to include last number

      

+2


source







All Articles