Introduction
I was looking for a more efficient way to write a LINQ query, when I accidentally stumbled across the Range()
method. I played a bit with it and came up with an interesting way to get an array of month names. The goal here is to get an array with 13 elements, with element 0 being empty, element 1 containing Jan, 2 containing Feb, and so on. Note that I said interesting, not simple. :) I'm a huge fan of LINQ and thought someone might appreciate the following.
Using the Code
Up to now, I've done it with either an explict array definition such as:
string[] months = { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
OR
By splitting a string
that contains the months and a delimiter such as:
string[] months = ",Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".Split(',');
Splitting a string
is less verbose and achieves the same result. It is slightly less efficient than the first snippet.
Both methods are good and will work well.
The next method is an interesting way to get the same result. It is really a one-liner, but I've split it up for readability.
string[] months = Enumerable
.Range(0, 13)
.Select
(r => r > 0 ? Convert.ToDateTime("20/" + r + "/2000").ToString("MMM") : "")
.ToArray();
The Range()
method defines a range starting at 0
and ending at 12
.
The Select()
method converts numeric values in the range to date if they're greater than 0
, and then formats it as string
in the format MMM, which is the short month format.
The ToArray()
method does exactly that, i.e., it converts the result to an Array
.
Points of Interest
The third snippet describes a different way of achieving the same result as the first two snippets. What appeals to me is that I could get an additional array with long month names, e.g., January, February, March, etc. by just changing the format string from MMM to MMMM when converting the DateTime
variable to string
. I agree that it might not necessarily be practical, as the second method is the least amount of code, but it was too interesting not to share.
History
- 10th July, 2015: Initial post