Aggregate Methods in LINQ

The aggregate methods are used to perform aggregate operations such as sum, count, average, finding minimum and maximum values etc. Following are sum of the most commonly used aggregate operators in LINQ.

  • Count and LongCount
  • Min and Max
  • Sum and Average

Count and LongCount

The Count operators counts the total number of items in the sequence. If a predicate is passed to it, it will count the total number of elements that match that predicate. LongCount also performs the same operation but it returns a 64 bit integer which can be used to store values greater than 2 billion.

Min and Max

Min and Max operators find the minimum and maximum value in the sequence respectively. If a predicate is passed to it, it will find the minimum and maximum value that match that predicate.

Sum and Average

Sum and Average operators calculate the sum and average of values in the sequence, respectively. If a predicate is passed to it, it will calculate the sum and average of values in the sequence that match that predicate.

Have a look at the following example to see the working of these functions.

´╗┐using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            string[] sequence1 = { "Joseph", "Juana", "Sara", "Mike", "Angel", "Victoria" };

            int total = sequence1.Count();
            Console.WriteLine(total); // 6 will be printed.

            total = sequence1.Count(v=>v.Contains("e"));
            Console.WriteLine(total); // 3 will be printed.

            int[] randomnums = { 12, 43, 53, 23, 67, 54, 101, 54, 83 };

            total = randomnums.Max();
            Console.WriteLine(total); // 101 will be printed.

            total = randomnums.Min();
            Console.WriteLine(total); // 12 will be printed.

            double val = randomnums.Average();
            Console.WriteLine(val); // average of items will be printed

            total = randomnums.Sum();
            Console.WriteLine(total); // sum of items will be printed

            Console.ReadKey();
        }
    }
}

Download the code

<<< LINQ Projection OperatorsElement Operators in LINQ >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .