Select from IEnumerable with Distinct/GroupBy and sorting — possible?

Viewed 30479

Say you have this:

class LogEntry
{
    int ID;
    int UserName;
    datetime TimeStamp;
    string Details;
}

and you have pulled a set of data like this:

ID  Username   Timestamp   Details
1   foo        1/01/2010   Account created
2   zip        2/02/2010   Account created
3   bar        2/02/2010   Account created
4   sandwich   3/03/2010   Account created
5   bar        5/05/2010   Stole food
6   foo        5/05/2010   Can't find food
7   sandwich   8/08/2010   Donated food
8   sandwich   9/09/2010   Ate more food
9   foo        9/09/2010   Ate food
10  bar        11/11/2010  Can't find food

What I want to do is select only the last single record (ie Sort on TimeStamp Descending) for each user (ie GroupBy Username). I can get my head around Distinct and GroupBy, but combining them in a single statement which also returns the non-distinct/grouped fields/properties AND sorts by timestamp is giving me a headache.

What should come out with the above example is:

ID  Username   Timestamp   Details
2   zip        2/02/2010   Account created
8   sandwich   9/09/2010   Ate more food
9   foo        9/09/2010   Ate food
10  bar        11/11/2010  Can't find food

I don't want to 'cheat' and resort to a long-winded way of doing it when I'm confident it can be done in a single LINQ statement.

1 Answers
Related