views:

47

answers:

4

I am trying to group by an CarId field , and then within each group, I want to sort on a DateTimeStamp field descending. The desired data would be for each Car give me the latest DateTimeStamp and only that 1 in the group.

I can get to this point, but having problems taking the top 1 off of the group and ordering the group by DateTimeStamp desc.

Here is what I have:

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 would desire:

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

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

Brickwall: Where I get stopped, is needing the CarId and DateTimeStamp in the group by clause, in order to later sort by the DateTimeStamp. Maybe the sorting of the date should be done in a separate function, not sure.

A: 

look into takeone that returns only first

Roadie57
A: 

Try this?

 var latest = Group1.OrderByDescending(x=>x.DateTimeStamp).FirstOrDefault();
p.campbell
Won't that just return the first *group*? Not the first item in each group?
Kirk Woll
@Kirk: Yes, it appears that the OP has them in separate groups, as each 'resultset' has separate result data and headers. My answer has `Group1` to highlight how it can be done with both groups.
p.campbell
How is your Group1 defined, does it contain Id and DateTimeStamp ?
RyBolt
A: 

use FirstOrDefault

Profeten
+2  A: 
data
    .GroupBy(
        x => x.CardId, 
        (x, y) => new { 
            Key = x, 
            Value = y.OrderByDescending(z => z.DateTimeStamp).First() 
        }
    );

This will group all the elements by CardId, then order the elements of each group by DateTimeStamp (descending), then pare down each group to only contain the first element. Finally, it returns an enumerable of "groups" (with the scare quotes since they're actually an anonymous type instead of an IGrouping) where each group has the one item you're seeking.

Kirk Woll
That did it! I did get an exception and had to use FirstOrDefault() instead of First(). Thanks!
RyBolt