How can I use Sum () in LINQ?
How can I use Sum () in LINQ?
411
27-Jul-2023
Updated on 28-Jul-2023
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
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.