How do I get the MAX row with a GROUP BY in LINQ query?

Viewed 116011

I am looking for a way in LINQ to match the follow SQL Query.

Select max(uid) as uid, Serial_Number from Table Group BY Serial_Number

Really looking for some help on this one. The above query gets the max uid of each Serial Number because of the Group By Syntax.

7 Answers
        using (DataContext dc = new DataContext())
        {
            var q = from t in dc.TableTests
                    group t by t.SerialNumber
                        into g
                        select new
                        {
                            SerialNumber = g.Key,
                            uid = (from t2 in g select t2.uid).Max()
                        };
        }
var q = from s in db.Serials
        group s by s.Serial_Number into g
        select new {Serial_Number = g.Key, MaxUid = g.Max(s => s.uid) }

This can be done using GroupBy and SelectMany in LINQ lamda expression

var groupByMax = list.GroupBy(x=>x.item1).SelectMany(y=>y.Where(z=>z.item2 == y.Max(i=>i.item2)));

Building upon the above, I wanted to get the best result in each group into a list of the same type as the original list:

    var bests = from x in origRecords
            group x by x.EventDescriptionGenderView into g
            orderby g.Key
            select g.OrderByDescending(z => z.AgeGrade)
            .FirstOrDefault();

    List<MasterRecordResultClaim> records = new 
                  List<MasterRecordResultClaim>();
    foreach (var bestresult in bests)
    {
        records.Add(bestresult);
    }

EventDescriptionGenderView is a meld of several fields into a string. This picks the best AgeGrade for each event.

Related