Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Build List of years as integers

Tags:

c#

list

linq

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?

like image 973
MegaMatt Avatar asked Nov 06 '10 17:11

MegaMatt


3 Answers

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.

like image 65
adrianbanks Avatar answered Oct 18 '22 01:10

adrianbanks


Use Enumerable.Range()

var MyList = Enumerable.Range(1930, 2010-1930+1).ToList();
like image 38
Jim Mischel Avatar answered Oct 18 '22 02:10

Jim Mischel


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();
like image 9
jb. Avatar answered Oct 18 '22 02:10

jb.