Free Web Development Online Tutorials, Learn to Code
Learn LINQ with C#, Language Integrated query with different Data Source

LINQ Sum method Example

Learn how to use SUM method in LINQ Query using C#

SUM method in LINQ Query C#

Enumerable.Sum is extension method, it sum of numeric values of any collection, Sum method comes under System.Linq namespace

Let's look at some examples below

Sum for Numeric Data Types
Total sum of values of all integer numbers in the list.

var _numbers = new List<int> { 10, 55, 5, 19, 9, 2};
Console.WriteLine( _numbers.Sum());// sum: 100

Sum method with Query Syntax
this is an example of LINQ query expression to get sum of any collection

var numberList = new List<int> { 10, 55, 5, 19, 9, 2};
int total = (from x in numberList select x).Sum();
Console.WriteLine(total); // sum: 100

LINQ Sum with Group By Example

In this example we learn how to use Sum with GroupBy to find out the score of each stream.

var studentsStream = new List<Student> { new Student { FullName = "Aruna", StreamId=1, Score = 10 },
new Student { FullName = "Janet", StreamId=2, Score = 9 },
new Student { FullName = "Ajay", StreamId=1, Score = 11 },
new Student { FullName = "Kunal", StreamId=2, Score = 13 },
new Student { FullName = "Chandra", StreamId=2, Score = 8 },
};
var groupScores =
from techStream in studentsStream
group techStream by techStream.StreamId into studentGroup
select new
{
Stream = studentGroup.Key,
GroupScore = studentGroup.Sum(x => x.Score),
    };

foreach (var scr in groupScores)
{
    Console.WriteLine(string.Format("{0}-{1}", scr.Stream, scr.GroupScore));
}

In above code we have calculated the Sum scrore of each stream, here is the result

1 - 21
2 - 30
Comment
Name
Email
Website
Subscribe
 
Learn LINQ .Net

LINQ Sum method Example in C#

linq Interview Questions Answers

LINQ C# examples | Join Asp.net MVC Course