Reputation:
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?
Upvotes: 1
Views: 345
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
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