Group By Sum in C# LINQ
Introduction
Before you get into this article,
If you did enough google to find solution for summing up an item in a group, yes thank you for landing here. This article describes calculating sum of a group in an object model using LINQ C# program.
Please ignore this step, If you have downloaded source code. If not after clicking above download link redirects to source repository as image below download the zipped file ( C# Visual Studio Project).
How do you define your problem here?
Yes that's the right question.
Let me describe a bit, In a school pick a class of students associated with subjects like (English, Math's, Science, Chemistry, Physics) marks. And noted each student is identified with an unique number called Student ID, now you would like to calculate sum of marks for each students in a class.
This is simple, apply group by in student class property to get result.
No, this isn't the appropriate answer.
Now consider you are tricked by there are duplicate Student ID's and Marks of each subject - How to handle duplicates?
This is where LINQ helps complicated problems in a line of code.
Before go into the solution, Let's design data model for student marks
In below class property ID denotes student Id and property Marks denotes subject marks student has scored.
Add Data to Student Marks?
In this practice, I used DataTable to add records into it. Why I used data table and not the latest class properties the reason is in this article below section explains of converting from List to a DataTable.
Below code section, adding data to data rows of two columns ID and Marks. If you note on the entry ID has duplicated 1 and 2.
Let's say this is the input, and you are expecting an output with group by ID sum
What is the Expected Result?
The data grouped by ID sum of marks value 1 which has marks 30 and 50 becomes 80, and similarly ID 2 marks of 0 and 100 becomes 100, then ID 3 mark is 45 remains.
1 50 + 30 = 80
2 0 + 100 = 100
3 45 = 45
ID | MARKS |
1 | 80 |
2 | 100 |
3 | 45 |
0 Comments