Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

LINQ One-liner to Get An Array Containing Month Names

0.00/5 (No votes)
9 Jul 2015 1  
The following tip contains a simple way to get an array of month names. It is a one liner, a rather trivial task - but I thought it was too cool not to share :).

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.

// The following line of code will get the month names into an array.
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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here