Real World
Real World

Reputation: 1719

LINQ orderby and group

Consider the following code

var res = from d in CalEntries
    group d by d.date.ToString("MMMM") into grp
    orderby grp.Key 
    select grp;

I have a list of objects in CalEntries where one member property is date of type DateTime. Currently this code returns me all the dates grouped by the month name however the order of the groups is alphabetic so November would appear before October for example. How can I modify this query to retain the grouping on the month name but to order the groups based on the months chronological order?

Upvotes: 1

Views: 111

Answers (2)

usr
usr

Reputation: 171246

It is really backwards to group by the name of the month if you don't care about the month name at all. Instead, group directly by the month number and sort by it. Don't compute with strings if the native format of your data is more suitable.

group x by x.Month into g
orderby g.Key
select new { MonthName = g.Key.ToString("MMMM"), Items = g.ToList() }

Upvotes: 2

Fratyx
Fratyx

Reputation: 5797

You could try:

orderby d.date.ToString("MM") ascending

Upvotes: 0

Related Questions