Linq Aggregate Method in C#

Linq Aggregate Method in C# with Examples

In this article, I am going to discuss the Linq Aggregate Method in C# with examples. Please read our previous article before proceeding to this article where we discussed the Linq Count method with some examples. As part of this article, we are going to discuss the following pointers.

  1. What is Linq Aggregate Method in C#?
  2. Multiple examples using both Method and Query syntax.
What is Linq Aggregate Method in C#?

The Linq Aggregate extension method performs an accumulative operation. There are three overloaded versions of this method is available in System.Linq namespace as shown in the below image.

Linq Aggregate Method in C#

Let us understand the use of the Aggregate method with some examples.

Example1: Comma-separated string.

Let us consider we have the following string array

string[] skills = { “C#.NET”, “MVC”, “WCF”, “SQL”, “LINQ”,  “ASP.NET”};

Our requirement is to combine all the above strings present in the skill array into a single comma-separated string as shown below.

C#.NET, MVC, WCF, SQL, LINQ, ASP.NET

Program without using Linq Aggregate method:

using System;
using System.Linq;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] skills = { "C#.NET", "MVC", "WCF", "SQL", "LINQ", "ASP.NET" };

            string result = string.Empty;

            foreach(string skill in skills)
            {
                result = result + skill + ", ";
            }

            //Find the index position of last comma
            int lastIndex = result.LastIndexOf(",");

            //Remove the last comma
            result = result.Remove(lastIndex);

            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}

Output:

Linq Aggregate Method in C# with Examples

Now let us see how to achieve the same output using the Linq Aggregate method.

Program using Linq Aggregate Method:
using System;
using System.Linq;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] skills = { "C#.NET", "MVC", "WCF", "SQL", "LINQ", "ASP.NET" };

            string result = skills.Aggregate((s1, s2) => s1 + ", " + s2);
            
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}

Output:

C# Aggregate Method

How does the above Aggregate Method work?

The lambda expression (s1, s2) => s1 + “, ” + s2 will be treated like s1 = s1 + “, ” + s2 where s1 will be accumulated for each item present in the collection. As a result, the Aggregate function will return the comma-separated string. Please have a look at how the comma-separated string is generated step by step.

  1. Step1. First “C#.NET” is concatenated with “MVC” to produce the result “C#.NET, MVC“.
  2. Step2. Result in Step 1 i.e. “C#.NET, MVC” is then concatenated with “WCF” to produce the result “C#.NET, MVC, WCF“.
  3. Step3: Result in Step 2 i.e. “C#.NET, MVC, WCF” is then concatenated with “SQL” to produce the result “C#.NET, MVC, WCF, SQL“.
  4. Step4: Result in Step 3 i.e. “C#.NET, MVC, WCF, SQL” is then concatenated with “LINQ” to produce the result “C#.NET, MVC, WCF, SQL, LINQ“.
  5. Step5: Result in Step 4 i.e. “C#.NET, MVC, WCF, SQL, LINQ” is then concatenated with “ASP.NET” to produce the final result “C#.NET, MVC, WCF, SQL, LINQ, ASP.NET” what we see in the output.
Example2: Product of integer numbers

Consider we have the following integer array

int[] intNumbers = { 3, 5, 7, 9 };

Our requirement is to compute the product of all numbers.

Program without using Aggregate Method:
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] intNumbers = { 3, 5, 7, 9 };

            int result = 1;
            foreach(int num in intNumbers)
            {
                result = result * num;
            }
            
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}
Program using Aggregate Method:
using System;
using System.Linq;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] intNumbers = { 3, 5, 7, 9 };

            int result = intNumbers.Aggregate((n1, n2) => n1 * n2);

            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}

How does the above Aggregate Method work?

  1. Step1: First it multiplies (3X5) to produce the result as 15
  2. Step2: Result of Step 1 i.e. 15 is then multiplied with 7 to produce the result as 105
  3. Step3: Result of Step 2 i.e. 105 is then multiplied with 9 to produce the final result as 945.
Aggregate Method with the seed parameter:

The second overloaded version of the Aggregate method takes the first parameter as the seed value to accumulate. The Second parameter is Func type delegate: Let us understand the use of the seed parameter with an example. Let us see how to pass the seed value as 2 with our previous example.

int result = intNumbers.Aggregate(2, (n1, n2) => n1 * n2);

The complete example is given below.

using System;
using System.Linq;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] intNumbers = { 3, 5, 7, 9 };

            int result = intNumbers.Aggregate(2, (n1, n2) => n1 * n2);

            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}

Output: 1980

How does it work?
  1. Step1: First it multiplies (2*3) to produce the result as 6
  2. Step2: Result of Step 1 i.e. 6 is then multiplied with 5 to produce the result as 30
  3. Step3: Result of Step 2 i.e. 30 is then multiplied with 7 to produce the result as 210.
  4. Step4: Result of Step 3 i.e. 210 is then multiplied with 9 to produce the final result as 1890.
Aggregate Method with Complex Type:

We are going to work with the following Employee class.

using System.Collections.Generic;
namespace LINQDemo
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Department { get; set; }

        public static List<Employee> GetAllEmployees()
        {
            List<Employee> listStudents = new List<Employee>()
            {
                new Employee{ID= 101,Name = "Preety", Salary = 10000, Department = "IT"},
                new Employee{ID= 102,Name = "Priyanka", Salary = 15000, Department = "Sales"},
                new Employee{ID= 103,Name = "James", Salary = 50000, Department = "Sales"},
                new Employee{ID= 104,Name = "Hina", Salary = 20000, Department = "IT"},
                new Employee{ID= 105,Name = "Anurag", Salary = 30000, Department = "IT"},
               
            };

            return listStudents;
        }
    }
}

Note: While working with the complex type we need to use either the second third overloaded version of the Aggregate method:

Example3:

The following example uses the Aggregate method to add the salary of all the employees.

using System;
using System.Linq;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int Salary = Employee.GetAllEmployees()
                            .Aggregate<Employee, int>(0,
                            (TotalSalary, emp) => TotalSalary += emp.Salary);
            
            Console.WriteLine(Salary);
            Console.ReadKey();
        }
    }
}

Please note here we passed the seed value as 0. Once you run the application, it gives you the output as expected.

Example4:

In the following example, we pass a string as the seed value to the Aggregate extension method. Here the seed value is “Employee Names”.

using System;
using System.Linq;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string CommaSeparatedEmployeeNames = Employee.GetAllEmployees().Aggregate<Employee, string>(
                                        "Employee Names : ",  // seed value
                                        (employeeNames, employee) => employeeNames = employeeNames + employee.Name + ", ");

            int LastIndex = CommaSeparatedEmployeeNames.LastIndexOf(",");
            CommaSeparatedEmployeeNames = CommaSeparatedEmployeeNames.Remove(LastIndex);

            Console.WriteLine(CommaSeparatedEmployeeNames);
            Console.ReadKey();
        }
    }
}

Output: Employee Names : Preety, Priyanka, James, Hina, Anurag

In the above example, the first parameter of the Aggregate method is the “Employee Names: ” string that will be accumulated with all employee names. The comma in the lambda expression will be passed as the second parameter.

Aggregate Method with Result Selector

The third overload version requires the third parameter of the Func delegate expression for the result selector so that we can formulate the result. In our previous example, once we get the comma-separated string then we remove the last comma using some additional logic. Let us see how we can do the same using the third parameter.

using System;
using System.Linq;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string CommaSeparatedEmployeeNames = Employee.GetAllEmployees().Aggregate<Employee, string, string>(
                                        "Employee Names : ",  // seed value
                                        (employeeNames, employee) => employeeNames = employeeNames + employee.Name + ",",
                                        employeeNames => employeeNames.Substring(0, employeeNames.Length - 1));
            
            Console.WriteLine(CommaSeparatedEmployeeNames);
            Console.ReadKey();
        }
    }
}

Output: Employee Names : Preety,Priyanka,James,Hina,Anurag

In the above example, we have specified a lambda expression i.e. employeeNames => employeeNames.Substring(0, employeeNames.Length – 1) to remove the last comma in the string result.

I hope you understood the need and use of the Linq Aggregate Method in C#. In the next article, I am going to discuss the Quantifier Operators in LINQ with examples.

Leave a Reply

Your email address will not be published. Required fields are marked *