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.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
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#
The
sequenceparameter is the sequence of values that you want to sum. Theselectorparameter 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
productstable. 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.