Tuesday, April 8, 2008

LINQ Grouping Example

I recently had the need to do some grouping on a SQL db table via LINQ. Records were grouped based on a single identifier field - but then to make them unique they had a version field that started at 0 and incremented whenever the record was modified (each modification created a new copy of the record with the incremented version#). So of course I needed to only pull the most recent versions of these records.

Example Records:

Identifier Version Data
1234ABC 000 ................ <- dont select this one
12BCD34 000 ................ <- select this one
1234ABC 001 ................ <- select this one
etc..

I've done this type of thing before with raw sql, but this was my first attempt at it via LINQ.


var recs = from trans in dc.Transactions
group trans by new
{
Identifier = trans.Identifier
} into grp
select new
{
Identifier = grp.Key.Identifier,
Version = grp.Max(t => t.Version)
};


Pretty simple once you get your head around the syntax. It simply groups on the Identifier column and only selects the Version with the highest number.

0 comments:

Post a Comment