In LINQ, how do I get the first record in a group?

c# c#-4.0 entity-framework linq linq-to-entities

Question

How to get the top element in the ordered groupings of data

I'm attempting to group using the CarId column, and then I want to sort each group using the DateTimeStamp field in decreasing order. The requested data would be the most recent DateTimeStamp for each Car, and just that one.

To sort the group by DateTimeStamp desc and remove the top 1 from the group, which I can do, is proving to be difficult.

I have the following: after the first group action

group 1
------------------------
CarId  DateTimeStamp 
1      1/1/2010
1      1/3/2010
1      3/4/2010

group 2
------------------------
CarId  DateTimeStamp 
2      10/1/2009
2      1/3/2010
2      9/4/2010

what I'd want would be just the first person on a list is arranged

    group 1
    ------------------------
    CarId  DateTimeStamp 
    1      3/4/2010

    group 2
    ------------------------
    CarId  DateTimeStamp 
    2      9/4/2010

Brickwall: Where I get stuck is when I want to subsequently sort by DateTimeStamp but I need the CarId and DateTimeStamp in the group by clause. I'm not sure, but maybe the date should be sorted in a different function.

1
15
3/21/2017 3:23:17 PM

Accepted Answer

data
    .GroupBy(
        x => x.CardId, 
        (x, y) => new { 
            Key = x, 
            Value = y.OrderByDescending(z => z.DateTimeStamp).FirstOrDefault() 
        }
    );

This will organize all of the components byCardId then sorting the components of each group byDateTimeStamp then reduce each group such that just the first element remains in each (descending). Finally, it produces an enumerable of "groups" (with the quotation marks since they are really an anonymous type rather than an enumerable).IGrouping Each category contains the one thing you're looking for.

17
12/12/2015 1:04:23 AM

Popular Answer

I personally find it simpler to comprehend the syntax of query expressions:

from x in data 
group x by x.CarId into grp
select new {
    CarId = x.CarId,
    Record = (from x in grp orderby z.DateTimeStamp descending).FirstOrDefault()
};


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow