Skilled in SEO, content writing, and digital marketing. Completed several years of working in many organizations including multinational companies. I love to learn new things in life that keep me motivated.
The Sum() method in LINQ is used to calculate the sum of a sequence of values. It can be used with any sequence of numeric values, such as integers, floats, doubles, and decimals.
The syntax for the Sum() method is as follows:
C#
var sum = sequence.Sum(selector);
The sequence parameter is the sequence of values that you want to sum. The
selector parameter is a function that takes a single element from the sequence and returns a numeric value.
For example, the following code uses the Sum() method to calculate the sum of all the numbers in an array:
C#
int[] numbers = { 1, 2, 3, 4, 5 };
var sum = numbers.Sum(x => x);
This code will first create an array of integers called numbers. Then, it will use the
Sum() method to calculate the sum of all the numbers in the array. Finally, it will store the sum in a variable called
sum.
The Sum() method can also be used with LINQ queries. For example, the following code uses the
Sum() method to calculate the sum of all the prices in a table of products:
C#
var products = new LinqToSqlSumDataContext().Products;
var sum = products.Sum(x => x.Price);
This code will first create a LINQ query for the products table. Then, it will use the
Sum() method to calculate the sum of all the prices in the table. Finally, it will store the sum in a variable called
sum.
Liked By
Write Answer
How can I use Sum () in LINQ?
Join MindStick Community
You have need login or register for voting of answers or question.
Aryan Kumar
28-Jul-2023The
Sum()
method in LINQ is used to calculate the sum of a sequence of values. It can be used with any sequence of numeric values, such as integers, floats, doubles, and decimals.The syntax for the
Sum()
method is as follows:C#
The
sequence
parameter is the sequence of values that you want to sum. Theselector
parameter is a function that takes a single element from the sequence and returns a numeric value.For example, the following code uses the
Sum()
method to calculate the sum of all the numbers in an array:C#
This code will first create an array of integers called
numbers
. Then, it will use theSum()
method to calculate the sum of all the numbers in the array. Finally, it will store the sum in a variable calledsum
.The
Sum()
method can also be used with LINQ queries. For example, the following code uses theSum()
method to calculate the sum of all the prices in a table of products:C#
This code will first create a LINQ query for the
products
table. Then, it will use theSum()
method to calculate the sum of all the prices in the table. Finally, it will store the sum in a variable calledsum
.