开发者

C#: Build List of years as integers

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 开发者_StackOverflownumbers 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();


So, while this has been answered (with good answers), why not create a methods which 'yields' (a generator method) -- Enumerable.Range is just such a method that is standard:

IEnumerable<int> InclusiveRange(int s, int e) {
   for (int i = s; i <= e; i++) {
     yield return i;
   }
}

var r = InclusiveRange(1930, 2010).ToList();

Happy coding.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜