Populating a list of integers in .NET
C#.NetListIntegerC# Problem Overview
I need a list of integers from 1 to x where x is set by the user. I could build it with a for loop eg assuming x is an integer set previously:
List<int> iList = new List<int>();
for (int i = 1; i <= x; i++)
{
iList.Add(i);
}
This seems dumb, surely there's a more elegant way to do this, something like the PHP range method
C# Solutions
Solution 1 - C#
If you're using .Net 3.5, Enumerable.Range is what you need.
> Generates a sequence of integral > numbers within a specified range.
Solution 2 - C#
LINQ to the rescue:
// Adding value to existing list
var list = new List<int>();
list.AddRange(Enumerable.Range(1, x));
// Creating new list
var list = Enumerable.Range(1, x).ToList();
See Generation Operators on LINQ 101
Solution 3 - C#
I'm one of many who has blogged about a ruby-esque To extension method that you can write if you're using C#3.0:
public static class IntegerExtensions
{
public static IEnumerable<int> To(this int first, int last)
{
for (int i = first; i <= last; i++)
{
yield return i;
}
}
}
Then you can create your list of integers like this
List<int> = first.To(last).ToList();
or
List<int> = 1.To(x).ToList();
Solution 4 - C#
Here is a short method that returns a List of integers.
public static List<int> MakeSequence(int startingValue, int sequenceLength)
{
return Enumerable.Range(startingValue, sequenceLength).ToList<int>();
}