Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do Max Aggregation in LINQ query syntax?

Tags:

c#

linq

max

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;
like image 505
Przemysław Banaszek Avatar asked Apr 08 '16 06:04

Przemysław Banaszek


People also ask

How do you find the maximum value in LINQ?

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#.

What is aggregate function LINQ?

In LINQ, aggregation functions are those functions which are used to calculate a single value from the collection of the values.

Can we use multiple where clause in LINQ?

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.


2 Answers

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);
like image 156
ASh Avatar answered Oct 12 '22 19:10

ASh


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);
like image 28
Ishikawa Avatar answered Oct 12 '22 20:10

Ishikawa