Simple select max

Posts   
 
    
yowl
User
Posts: 266
Joined: 11-Feb-2008
# Posted on: 23-Mar-2017 15:26:30   

Hi,

I should know this but.

If I want to do the SQL "select max(c) from t where a = 1"

How do I write the linq for that?

Pseudo something like:

from pc in meta.tl
                where a == 1
                select pc.c.Max()

There's some VB examples at https://www.llblgen.com/documentation/5.1/LLBLGen%20Pro%20RTF/Using%20the%20generated%20code/Linq/gencode_linq_generalusage.htm but not for c#

Walaa avatar
Walaa
Support Team
Posts: 14946
Joined: 21-Aug-2005
# Posted on: 24-Mar-2017 10:06:27   

You have more than one option.

Option #1: Grouping, and returning a resultset.

var q = from od in metaData.OrderDetail
        where od.ProductId == 1
        group od by od.ProductId into g
        select new
        {
            MaxQuantity = g.Max(x => x.Quantity)
        };
var result = q.ToList();

Option #2: ScalarQuery

var q = from od in metaData.OrderDetail
        where od.ProductId == 1
        select od;

var result = q.Max(x=>x.Quantity);

Option #3: ScalarQuery, in the simplest form

var q = from od in metaData.OrderDetail
        where od.ProductId == 1
        select od.Quantity;

var result = q.Max();