How to get MAX string with GROUP BY query in LINQ?

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

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

We are sincerely looking for some help in this matter. The above query gets the maximum uid for each serial number due to Group By syntax.

+70
linq linq-to-sql
Oct 01 '08 at 14:11
source share
5 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() }; } 
+75
01 Oct '08 at 14:34
source share
 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) } 
+56
Oct 01 '08 at 14:37
source share

I checked DamienG's answer in LinqPad. Instead

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

it should be

 g.Max(s => s.uid) 

Thank!

+19
Jul 24 '10 at 12:24
source share

In the form of a chain of methods:

 db.Serials.GroupBy(i => i.Serial_Number).Select(g => new { Serial_Number = g.Key, uid = g.Max(row => row.uid) }); 
+9
Aug 21 '13 at 17:48
source share

The answers are “OK”, if you need only these two fields, but for a more complex object, perhaps this approach can 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 avoids "pick a new one"

+5
Feb 24 '15 at 12:50
source share



All Articles