Background
I found myself developing a small sample code learning LINQ.
I wanted to find data based on dates.
Rather than to display the month as a number, I opted to display as a name.
In essence to be able to hard code the number 3 for the 3rd month, yet “beautifully” display the entry as March.
Sample Code
Ample explanation came from:-
How to list all month names, e.g. for a combo?
Link
mmmeff
var months1 = Enumerable.Range(1, 12) .Select ( i => new { monthNumber = i , monthName = DateTimeFormatInfo.CurrentInfo.GetMonthName(i) } );
Tiago Ávila
tiagoavila.com.br
Alfenas, Brazil
Link
var months2 = Enumerable.Range(1, 12) .Select ( i => new { monthNumber = i , monthName = DateTimeFormatInfo.CurrentInfo.GetMonthName(i) } );
SeanH
Dictionary<int, string> months3; months3 = Enumerable.Range(1, 12).Select ( i => new KeyValuePair<int, string> ( i , System.Globalization.DateTimeFormatInfo.CurrentInfo.GetMonthName(i) ) ).ToDictionary ( x => x.Key , x => x.Value );
Yona
string[] months4 = DateTimeFormatInfo.CurrentInfo.MonthNames; List<string> months4AsList = months4.ToList();
DivineOps
var months5 = DateTimeFormatInfo.CurrentInfo.MonthNames .Where ( p=>!string.IsNullOrEmpty(p) ) .Select ( (item, index) => new { monthNumber = index + 1 , monthName = item } );
Maher Ben Issa
var months6 = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames .TakeWhile ( m => m != String.Empty ) .Select ( (m,i) => new { monthNumber = i+1 , monthName = m } ) .ToList();
Observation
Various StackOverflow contributors handle the empty entry in novel ways.
-
- mmmeff and Tiago Ávila
- Enumerable.Range(1, 12)
- SeanH
- Enumerable.Range(1, 12)
- Dictionary Object
- Yona
- Used the plain DateTimeFormatInfo.CurrentInfo.MonthNames
- And, kept the empty last entry
- DivineOps
- Filters out the empty entry using the where clause ( string.IsNullOrEmpty )
- Sample Code
var months5 = DateTimeFormatInfo.CurrentInfo.MonthNames .Where ( p=>!string.IsNullOrEmpty(p) )
- Maher Ben Issa
- Filters out the empty entry by using the TakeWhile clause
- Sample Code
CultureInfo.CurrentCulture.DateTimeFormat.MonthNames .TakeWhile ( m => m != String.Empty )
- mmmeff and Tiago Ávila
Code Sharing
- GitLab
- .Net – LINQ – calendar – month
Link
- .Net – LINQ – calendar – month
On Line Lab
- OnlineGDB
- .Net – LINQ – calendar – month
Link
- .Net – LINQ – calendar – month
Summary
StackOverflow is a good thing.
Like Dela, sometimes you find mushiness in your fav programming language.
Hopefully someone hints before you knock your head against the wall too many times.
Dedicating
Dedicating to StackOverflow.
The engineering team and the unsurpassable contributors.
[…] Blog Post Link […]