Home »
.Net »
C# Programs
C# - Example of LINQ Aggregate() Method | Total of Employee's Salaries
Learn, how to calculate the total of employee's salaries using the Aggregate() method in C#?
By Nidhi Last updated : April 01, 2023
Here, we will an Employee class and then find the total of all employees using Linq Aggregate() method. Then print the total of salary on the console screen.
C# program to calculate the total of employee's salaries using the Aggregate() method
The source code to calculate the total of employee's salaries using the Aggregate() method, is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# program to calculate the total of employee's salary
//using the Aggregate() method.
using System;
using System.Linq;
using System.Collections.Generic;
public class Employee
{
int ID;
string Name;
int Salary;
string Department;
static void Main(string[] args)
{
int TotalSalary = 0;
List<Employee> employees = new List<Employee>()
{
new Employee {ID=101, Name="Amit " , Salary=4000,Department="ABC"},
new Employee {ID=102, Name="Amit " , Salary=3000,Department="XYZ"},
new Employee {ID=103, Name="Salman" , Salary=3000,Department="ABC"},
new Employee {ID=104, Name="Ram " , Salary=2000,Department="XYZ"},
new Employee {ID=105, Name="Shyam " , Salary=7000,Department="ABC"},
new Employee {ID=106, Name="Kishor" , Salary=5000,Department="XYZ"},
};
TotalSalary=employees.Aggregate<Employee, int>(0, (sum, e) => sum += e.Salary);
Console.WriteLine("Total Salary : "+TotalSalary);
}
}
Output
Total Salary : 24000
Press any key to continue . . .
Explanation
In the above program, we created the Employee class that contains the ID, Name, Salary, Department, and Main() method. In the Main() method, we created a list of employees.
TotalSalary=employees.Aggregate<Employee, int>(0, (sum, e) => sum += e.Salary);
In the above statement, we calculated the total of all employee's salaries using the Aggregate() method and then print the total of salary on the console screen.
C# LINQ Programs »