twsmale
twsmale

Reputation: 138

LINQ Group by with sort

I know I could do this outside of a LINQ query, but I wondered if it was possible to do so within one.

I would like to submit a query where I'm retrieving the most recent item with a distinct ID associated with it.

Say I have the following objects:

{
    ItemDescription: 'Object 1',
    ItemDate: 1/1/2016,
    ItemTypeId: 1
},
{
    ItemDescription: 'Object 2',
    ItemDate: 1/1/2016,
    ItemTypeId: 2
},
{
    ItemDescription: 'Object 3',
    ItemDate: 3/1/2016,
    ItemTypeId: 1
},

I would like a query to return objects 2 and 3 (since 3 was a more recent version of ItemTypeId=1.

It should (I think) be something like the following:

var recentItems = (from s in db
                   orderby s.ItemDate descending
                   group s by s.ItemTypeId into uniqueItems
                   select uniqueItems.FirstOrDefault()).ToList();

However, the FirstOrDefault overrides the ordering.

Any thoughts?

Upvotes: 0

Views: 85

Answers (1)

Zein Makki
Zein Makki

Reputation: 30022

This should work:

var recentItems = (from s in db
                   group s by s.ItemTypeId into uniqueItems
                   select uniqueItems.OrderByDescending(x=> x.ItemDate ).FirstOrDefault())
                                                                        .ToList();

Upvotes: 2

Related Questions