obautista
obautista

Reputation: 3773

How do I order a Group by and Order by a result using Linq

I have datetime values (e.g. 12/01/2010 10:10:222..) How can I display just the year in desc order? For example, 2011, 2010, 2009, 2008, etc.. I need to group by just the year part of the field and return that. I actually need to return the year and the name. I need to use the name for other functionality, which is why I need the 2 values.

Thanks for any help...

Upvotes: 0

Views: 125

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499860

It's not really clear what you mean, but you might just want something like:

var query = collection.GroupBy(record => record.DateProperty.Year)
                      .OrderBy(group => group.Key);

If that's not what you're after, please provide more details - ideally some sample input and desired output.

If you only want one entry from each group and you're happy to take any arbitrary one to get the name, and you only want the year, you could do:

var query = collection.GroupBy(record => record.DateProperty.Year)
                      .Select(g => new { Year = g.Key, Name = g.First().Name })
                      .OrderBy(x => x.Year);

Upvotes: 2

Richard
Richard

Reputation: 22016

I would use the Distinct and OrderByDescending extensions:

var years = IQueryableObject
                 .Distinct(x => x.Year).OrderByDescending(x => x.Year).ToList();

Upvotes: 2

Related Questions