简体   繁体   中英

LINQ Query, Return Max Value with Where Clause

I'm working on an API; how can I set my linq query up to return the max value with a where condition?

See the example code below; I can return the max value of the field I want, but I need to filter it where another column value equals something.

var lot = db.ShrinkLotData.Where(x => x.SupplierMfgLot.ToLower() == label.SupplierMfgLot.ToLower() && x.CatPattern.ToLower() == label.CatPattern.ToLower())
                    .SingleOrDefaultAsync();

    if (lot.Result == null)
    {
        var lots = db.ShrinkLotData.Where(x => x.CatPattern.ToLower() == label.CatPattern.ToLower());

        int internallot = db.ShrinkLotData.Max(x => x.InternalLotNum).Value;

        return Ok(lot);
    }

    return Ok(lot);
}

for the internallot, I want to return the highest value using similar syntax as the lots syntax.. (Where the catpattern equals a specific value)

What am I overlooking?

Thanks!

If I understand correctly, you basically need to use Where and Max together, so that you can select max value with a where condition.

db.ShrinkLotData.Where(x => x.CatPattern.ToLower() == label.CatPattern.ToLower()).Max(x => x.InternalLotNum).Value;

More Info : Composability of Queries :

..., you compose them in method syntax by chaining the method calls together. This is what the compiler does behind the scenes when you write queries by using query syntax. And because a query variable does not store the results of the query, you can modify it or use it as the basis for a new query at any time, even after it has been executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM