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
Well, you can just put var list = new List<IMyCustomType>(); list. Add(new MyCustomTypeOne()); list. Add(new MyCustomTypeTwo()); list. Add(new MyCustomTypeThree()); on one line.
Use the AddRange() method to append a second list to an existing list. list1. AddRange(list2); Let us see the complete code.
If you're using .Net 3.5, Enumerable.Range is what you need.
Generates a sequence of integral numbers within a specified range.
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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With