I'd like to create a C# List
of integers, from say 1930 to 2010. Off the top of my head, the only way I can think of to do this is to use a for
or while
loop to loop through each integer between the numbers and add them to the List
individually.
I know C# lists have a lot of interesting methods, especially when you're using Linq. Can anyone think of a more efficient way of doing this?
Enumerable.Range(1930, 81)
(MSDN docs) will get you an enumerable containing what you want. The first parameter is the starting value and the second is the number of items. You need 81 instead of 80 because you want 1930 to 2010 inclusive.
If you explicitly want it as a List
, use Enumerable.Range(1930, 81).ToList()
.
This method is probably no different in terms of efficiency, but is more succinct code.
Use Enumerable.Range()
var MyList = Enumerable.Range(1930, 2010-1930+1).ToList();
The other two answers are correct, using Enumberable.Range()
is the quick/easy way to do this, but I would add on piece. Use DateTime.Now.Year
so you don't have to fix the code every year. In two months, using a hard-coded value for the second parameter would have made this out of date.
List<int> listYears = Enumerable.Range(1930, DateTime.Now.Year - 1930 + 1).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