user4864716
user4864716

Reputation:

Is there a simple LINQ method to sort a list by Month?

Pretend we have a simple model like this, where one column is "Month" as a three-letter string.

public class SampleModel
{            
    public int ID { get; set; }
    public string Column1 { get; set; }
    public string Month { get; set; }
    public string Column2 { get; set; }
}

If we wanted to sort that model by Month, A LINQ statement like

query.OrderBy(m =>m.Month)

would produce the following alphabetical sort because Month is a string.

Is there a simple way to sort Month chronologically?

Sample table

Upvotes: 1

Views: 345

Answers (2)

Habib
Habib

Reputation: 223282

You can parse the Month part to DateTime and then use OrderBy like:

var orderedCollection = list.OrderBy(r => 
                   DateTime.ParseExact(r.Month, "MMM", CultureInfo.InvariantCulture));

With parsing like this, the day,year part will be selected to current date. Although that will be irrelevant for your sort

Upvotes: 3

Daniel A. White
Daniel A. White

Reputation: 190966

You could do it by storing the data in a lookup table/dictionary, or an enum for that matter. This works provided you are using LINQ to Objects, not any fancy expression based LINQ.

Dictionary<string, int> months = new Dictionary<string, int>();
months.Add("Jan", 0);
// and so on

query.OrderBy(m => months[m.Month]);

This solution works well for other types of data, not just months.

Upvotes: 5

Related Questions