C# .NET: LINQ - Pull Recent Objects For Each Object in a GroupBy Clause

1/25/2013 10:37:41 AM

I have a SQL table with mulitple entries per person. I want to pull the most recent entry for each person, grouped by a userId and orderdby another field.

var ids = from scores in this.Db.Scores		   
		   group scores by scores.UserId into grp
		   let MostRecentScores = grp.Max(x => x.Id)
		   select MostRecentScores;

var query = from scores in this.Db.Scores
			where ids.Contains(scores.Id)			
			select scores;

return query.ToList();