LINQ method syntax
var methodSyntax = VersionControls.Where(x => !x.Removed).Max(x => x.VersionID);
LINQ query syntax
var querySyntax = from x in VersionControls
where !x.Removed
// how to do Max Aggregation in LINQ query syntax???
select x;
In LINQ, you can find the maximum element of the given sequence by using Max() function. This method provides the maximum element of the given set of values. It does not support query syntax in C#, but it supports in VB.NET. It is available in both Enumerable and Queryable classes in C#.
In LINQ, aggregation functions are those functions which are used to calculate a single value from the collection of the values.
Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one.
MSDN documentation says about Query Syntax and Method Syntax in 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 can't express everything that method syntax can
check how to combine them for Min and Max in this answer
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. That's why I would chain a DefaultIfEmpty(defaultElementValue)
just before the Max()
for safety issues. This way, ASh's solution would become :
var mixedSyntax = (from x in VersionControls
where !x.Removed
select x).DefaultIfEmpty(defaultVersionControlObject)
.Max(x => x.VersionID);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With