2

Possible Duplicate:
Linq orderby, start with specific number, then return to lowest

I need to create a ComboBox that lists the months of the year, but need it to start with the current month, and then the rest in month order, e.g.:

October
November
December
January
February
March
etc.....

The data source is a list of months in a database, which are numbered according to month number (i.e. January = 1, etc.) and then manipulated to give a datetime

How can I sort this list in C# so that I get the order I want?

TIA.

Community
  • 1
  • 1
slowhand
  • 39
  • 1
  • 2

4 Answers4

7
string[] months = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
var ordered = months.Skip(DateTime.Today.Month - 1)
                    .Concat(months.Take(DateTime.Today.Month - 1))
                    .Where(s=>!String.IsNullOrEmpty(s))
                    .ToList();
L.B
  • 114,136
  • 19
  • 178
  • 224
3

Use DateTimeFormatInfo.GetMonthName methoed

List<string> list = new List<string>();
DateTimeFormatInfo dtFI = new DateTimeFormatInfo();
DateTime currentDate = DateTime.Now;
DateTime nextyearDate = currentDate.AddYears(1).AddDays(-1);
while (currentDate < nextyearDate)
{
    list.Add(dtFI.GetMonthName(currentDate.Month));
    currentDate = currentDate.AddMonths(1);
}

This will create a new list of months, starting from current month.

Habib
  • 219,104
  • 29
  • 407
  • 436
2

Another take on this with LINQ:

// month name source, use what you prefer
var monthNames = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
var sorted = Enumerable.Range(1, 12).Zip(monthNames, Tuple.Create)
            .OrderBy(t => (t.Item1 - DateTime.Today.Month + 12) % 12)
            .Select(t => t.Item2)
            .ToArray();
Jon
  • 428,835
  • 81
  • 738
  • 806
0

You can get the lists of months in C# with List<DateTime> monthNames = DateTimeFormatInfo.CurrentInfo.MonthNames.ToList();. It get a List<DateTime> with 13 elements (a null month name at the end, but you can always remove the last element monthNames.RemoveAt(monthNames.Count - 1); http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.monthnames.aspx

To reorder this list you can get the current month number index using DateTime.Now.Month.ToString("00");, and restructure the list newMonthNames = monthNames.GetRange(index, 12 - index).AddRange(monthNames.GetRange(0, index);

There are many ways to do it, like others have shown.

Coral Doe
  • 1,925
  • 3
  • 19
  • 36