Below are the most used aggregation functions in the Linq class with examples. First, add the namespaces as shown below:

    using System.Collections.Generic;
    using System.Linq;

Now, create a list of type integer and assign a few variables to it.

    List<int> list = new List<int>() { 1, 2, 3, 4, 5 };

LINQ Sum Function

It returns the sum of all values in the numeric collection and zero for an empty list.

    int result = list.Sum(); // Returns 15

LINQ Max Function

It returns the maximum value from the numeric collection

    int result = list.Max(); // Returns 5

If the list is empty, an InvalidOperationException exception will be thrown.

LINQ Min Function

It will return the minim value of the numeric collection.

    int result = list.Min(); // Returns 1

It throws an InvalidOperationException exception for an empty list.

LINQ Count Function

It will return the number of items in a numeric collection.

    int result = list.Count(); // Returns 5

LINQ Average Function

Returns the average of the list numeric collection.

    double result = list.Average(); // Returns 3

An InvalidOperationException exception will be thrown for an empty list.

Related Artiles

Last modified: September 28, 2019

Comments

Write a Reply or Comment

Your email address will not be published.