简体   繁体   English

LINQ 查询,使用 Where 子句返回最大值

[英]LINQ Query, Return Max Value with Where Clause

I'm working on an API;我正在开发一个 API; how can I set my linq query up to return the max value with a where condition?如何设置我的 linq 查询以返回具有 where 条件的最大值?

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)对于 internallot,我想使用与 lot 语法类似的语法返回最高值..(其中 catpattern 等于特定值)

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.如果我理解正确的话,您基本上需要一起使用WhereMax ,以便您可以使用 where 条件选择最大值。

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.并且由于查询变量不存储查询的结果,您可以随时修改它或将其用作新查询的基础,即使在执行之后也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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