Updated April 5, 2023
Introduction to LINQ Sum
LINQ sum is a method that comes under the aggregate functions; this method is used to calculate the sum or total numeric values present in the collections or lists. This query syntax supports VB.Net, and in C#, it is available in Queryable and Enumerable classes. The extension method Enumerable.Sum comes from the namespace System.Linq. The return value of it is the sum of numeric values in the collection or list. It works with int, decimal, double, float, nullable, non-nullable values.
Syntax:
Given below is the syntax mentioned:
int[] _sumValues = { 10,20,30,40,50 };
int _result = _ sumValues .Sum();
var _listValues= new List<int>{2,4,6,8};
int _result= _ listValues.sum();
How does Sum work in LINQ?
The sum() method is the extension of Enumerable.Sum which included in the namespace System.Linq. The sum() function calculates the sum of items which present in the list or collection, and it returns the sum of numeric values as a result. It works with int, decimal, double, float, nullable, non-nullable values.
Let’s see the working flow with several examples.
Firstly we start with the integer numbers to get the sum of values from the list of integers.
var _numValues = new List<int> {2,3,4,5};
int _result = _ numValues.Sum(); // Output – 14
And next, we go on with the decimal numbers to get the sum of values from the list of decimal numbers.
var _numValues = new List<decimal> {3.1m, 3.2m, 4.1m, 5.3m};
int _result = _ numValues.Sum(); // Output – 15.7
Let’s see the empty collection in the method, to call the sum on the empty collection, which returns as 0.
var _numValues = new List<int> (); // empty list
int _result = _ numValues.Sum(); // Output – 0
If the nullable integers present in the collection, what will be the expected result, let’s see the sum of values from the list of nullable integers.
var _numValues = new List<int> {4, 7, null, 3};
int _result = _ numValues.Sum(); // Output – 14
By using the LINQ query expression, we get the sum of numeric values in a collection.
var listV = new List<int> {4, 4, 2, 4, 2, 4};
int _result = (from i in listV select i) .Sum(); // Output – 20
Examples of LINQ Sum
Given below are the examples mentioned:
The sum() method is the extension of Enumerable.Sum which included in the namespace System.Linq. The sum() function calculates the sum of items which present in the list or collection, and it returns the sum of numeric values as a result.
Example #1
Code:
using System;
using System. Linq;
namespace Example_1
{
class Program_A
{
static void Main(string[] args)
{
int[] _numValues = { 5, 10, 15, 20, 25 };
Console.WriteLine("LINQ Sum() Method:\n");
int _result = _numValues.Sum(); //_numValues.Sum() is used to add the values
Console.WriteLine("To calculating the sum of elements in the list:");
Console.WriteLine("Sum is {0}", _result);
Console.ReadLine();
}
}
}
Explanation:
- The above program explains the sum function is used to calculate the sum of the elements in the list ” numValues”.
Output:
Example #2
Code:
using System;
using System. Linq;
namespace Example_2
{
class Program_B
{
static void Main(string[] args)
{
int[] _numValues = { 15, 10, 8, 9, 7 };
Console.WriteLine("LINQ Sum() - Using Query Method:\n");
//by using Query method
int _query = (from num in _numValues
select num).Sum();
Console.WriteLine("To calculate the sum of elements using Query Syntax:");
Console.WriteLine("Result is: " + _query);
Console.ReadLine();
}
}
}
Output:
Example #3
In the following program, the method is applied with both query and method format, which explained with the employee details; sum () is used to calculate the salary of the employees using both formats.
Code:
using System;
using System.Linq;
using System.Collections.Generic;
namespace LINQDemo
{
public class Employee
{
public int empID_ { get; set; }
public string Employee_Name { get; set; }
public int Employee_Salary { get; set; }
public string Employee_Department { get; set; }
public static List<Employee> EmployeeDetails()
{
List<Employee> listStudents = new List<Employee>()
{
new Employee{ empID_ = 1001,Employee_Name = "Smith", Employee_Salary = 25000, Employee_Department = "Networking"},
new Employee{ empID_ = 1002,Employee_Name = "Prem", Employee_Salary = 35000, Employee_Department = " Designing "},
new Employee{ empID_= 1003,Employee_Name = "Peter", Employee_Salary = 50000, Employee_Department = " Designing "},
new Employee{ empID_ = 1004,Employee_Name = "Rock", Employee_Salary = 20000, Employee_Department = " Networking "},
new Employee{ empID_ = 1005,Employee_Name = "Ajmal", Employee_Salary = 35000, Employee_Department = " Networking "},
new Employee{ empID_ = 1006,Employee_Name = "Sijae", Employee_Salary = 25000, Employee_Department = " Networking "},
new Employee{ empID_ = 1007,Employee_Name = "Shasha", Employee_Salary = 38000, Employee_Department = " Networking "},
new Employee{ empID_ = 1008,Employee_Name = "James", Employee_Salary = 18000, Employee_Department = "Designing"},
new Employee{ empID_= 1009,Employee_Name = "Prethiv", Employee_Salary = 52000, Employee_Department = " Designing "},
new Employee{ empID_ = 1010,Employee_Name = "Angath", Employee_Salary = 32000, Employee_Department = " Designing "}
};
return listStudents;
}
static void Main(string[] args)
{
var totalSalary_method = Employee.EmployeeDetails()
.Sum(emp => emp.Employee_Salary );
var totalSalary_query = (from emp in Employee.EmployeeDetails()
select emp).Sum(e => e.Employee_Salary );
Console.WriteLine("\nLINQ Sum() in Query and Method Format\n");
Console.WriteLine("\nEMPLOYEE DETAILS");
Console.WriteLine("Sum Of Employee Salary = " + totalSalary_method);
//Using Method Syntax
var total_Salary = Employee.EmployeeDetails()
.Where(emp => emp.Employee_Department == " Networking ")
.Sum(emp => emp.Employee_Salary );
//Using Query Syntax
var _totalSalary_QS = (from emp in Employee.EmployeeDetails()
where emp.Employee_Department == " Networking "
select emp).Sum(e => e.Employee_Salary );
Console.WriteLine("\nUsing Query Syntax");
Console.WriteLine("Total Salary of Networking Department " + _totalSalary_QS);
var _totalSalary_MS = Employee.EmployeeDetails()
.Where(emp => emp.Employee_Department == " Networking ")
.Sum(emp => emp.Employee_Salary ); //method format
var totalSalary_res = (from emp in Employee.EmployeeDetails()
where emp.Employee_Department == " Networking "
select emp).Sum(e => e.Employee_Salary ); //query format
Console.WriteLine("\nUsing Method Syntax");
Console.WriteLine("Total Salary of Networking Department: " + _totalSalary_MS);
Console.ReadKey();
}
}
}
Output:
Conclusion
In this article, we saw one of the aggregate function called LINQ Sum() explained programmatically using both in query and method format; by using a method, we can easily return the sum of numeric values in the collection or list.
Recommended Articles
This is a guide to LINQ Sum. Here we discuss the introduction, how sum works and examples for a better understanding. You may also have a look at the following articles to learn more –