My particular example is fairly complex but I think the concept would apply equally to something like a logging system so I'll use that instead for ease of explanation. It's a ficticious example, please don't harp on or agonise over what is achitectually, programatically or morally wrong with the example itself :)
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 to a lesser extent GroupBy, but combining all of these 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 performance isn't critical here and I'm moderately confident it can be done in a single LINQ statement.