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

.NetLinqLinq to-Sql

.Net Problem Overview


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.

.Net Solutions


Solution 1 - .Net

        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()
                        };
        }

Solution 2 - .Net

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) }

Solution 3 - .Net

In methods chain form:

db.Serials.GroupBy(i => i.Serial_Number).Select(g => new
	{
		Serial_Number = g.Key,
		uid = g.Max(row => row.uid)
	});

Solution 4 - .Net

I've checked DamienG's answer in LinqPad. Instead of

g.Group.Max(s => s.uid)

should be

g.Max(s => s.uid)

Thank you!

Solution 5 - .Net

The answers are OK if you only require those two fields, but for a more complex object, maybe this approach could be useful:

from x in db.Serials 
group x by x.Serial_Number into g 
orderby g.Key 
select g.OrderByDescending(z => z.uid)
.FirstOrDefault()

... this will avoid the "select new"

Solution 6 - .Net

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)));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSpoiledTechie.comView Question on Stackoverflow
Solution 1 - .NettvanfossonView Answer on Stackoverflow
Solution 2 - .NetDamienGView Answer on Stackoverflow
Solution 3 - .NetLu55View Answer on Stackoverflow
Solution 4 - .Netdenis_nView Answer on Stackoverflow
Solution 5 - .NetJavierView Answer on Stackoverflow
Solution 6 - .NetAbhas BhoiView Answer on Stackoverflow