Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 476
SpoiledTechie.com Avatar asked Oct 01 '08 14:10

SpoiledTechie.com


People also ask

How do you Select records with Max ID that GroupBy multiple columns in LINQ to SQL?

In SQL, it is very simple to do: SELECT * FROM [dbo]. [tblOrderDeliveryGroup] t1 WHERE [DeliveryGroupId] IN ( SELECT MAX([DeliveryGroupId]) FROM [dbo]. [tblOrderDeliveryGroup] t2 WHERE (t1.

How can we do a GroupBy using LINQ query?

Grouping is a very powerful feature provided by LINQ that transforms a collection in groups where each group has a key associated with it. Note: GroupBy performs a deferred execution which means the query is only executed when the records are processed using a foreach loop.

What does GroupBy return in LINQ?

A LINQ query can end with a GroupBy or Select clause. The result of GroupBy operators is a collection of groups. For example, GroupBy returns IEnumerable<IGrouping<TKey,Student>> from the Student collection: Return type of GroupBy()

On which datasources do LINQ queries work?

In a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, . NET collections, and any other format for which a LINQ provider is available.


2 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()                         };         } 
like image 107
tvanfosson Avatar answered Sep 28 '22 02:09

tvanfosson


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) } 
like image 29
DamienG Avatar answered Sep 28 '22 03:09

DamienG