Reputation: 1075
Looking for linq query to fill a list with month + year for example (January 2012)
starting form current month
var currentdate = System.DateTime.Now
If Dec 2011 is the current month then list should be like this
December 2011 January 2012 ...... November 2012
Upvotes: 3
Views: 2148
Reputation: 9323
I'm editing to turn my sample code into a method that I might almost use in production because it's more testable and culture-aware:
public IEnumerable GetMonths(DateTime currentDate, IFormatProvider provider)
{
return from i in Enumerable.Range(0, 12)
let now = currentDate.AddMonths(i)
select new
{
MonthLabel = now.ToString("MMMM", provider),
Month = now.Month,
Year = now.Year
};
}
This outputs (on a French computer):
Upvotes: 6
Reputation: 115897
var months =
Enumerable.Range(0, 12).
Select(n => DateTime.Today.AddMonths(n)).
Select(d = new { Year = d.Year, Month = d.Month });
Upvotes: 8