简体   繁体   English

如何在LINQ查询语法中执行Max Aggregation?

[英]how to do Max Aggregation in LINQ query syntax?

LINQ method syntax LINQ 方法语法

var methodSyntax = VersionControls.Where(x => !x.Removed).Max(x => x.VersionID);

LINQ query syntax LINQ 查询语法

var querySyntax = from x in VersionControls
                  where !x.Removed
                  // how to do Max Aggregation in LINQ query syntax???
                  select x;

MSDN documentation says about Query Syntax and Method Syntax in LINQ MSDN文档说明了LINQ中的查询语法和方法语法

Query syntax and method syntax are semantically identical, but many people find query syntax simpler and easier to read. 查询语法和方法语法在语义上是相同的,但许多人发现查询语法更简单,更易于阅读。 Some queries must be expressed as method calls. 某些查询必须表示为方法调用。 For example, you must use a method call to express a query that retrieves the number of elements that match a specified condition. 例如,必须使用方法调用来表示检索与指定条件匹配的元素数的查询。 You also must use a method call for a query that retrieves the element that has the maximum value in a source sequence. 您还必须对查询使用方法调用,以检索源序列中具有最大值的元素。

Query syntax cant express everything that method syntax can 查询语法无法表达方法语法可以实现的所有内容

check how to combine them for Min and Max in this answer 在这个答案中检查如何将它们组合为Min和Max

var mixedSyntax = (from x in VersionControls
                  where !x.Removed
                  select x).Max(x => x.VersionID);

You have to keep in mind that the Max() method will throw an exception whenever the source collection is empty. 您必须记住,只要源集合为空, Max()方法就会抛出异常 That's why I would chain a DefaultIfEmpty(defaultElementValue) just before the Max() for safety issues. 这就是为什么我会在Max()之前链接DefaultIfEmpty(defaultElementValue) Max()以解决安全问题。 This way, ASh 's solution would become : 这样, ASh的解决方案将成为:

var mixedSyntax = (from x in VersionControls
                  where !x.Removed
                  select x).DefaultIfEmpty(defaultVersionControlObject)
                           .Max(x => x.VersionID);

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

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