'How to calculate percentage in Entity Framework

Let's say I have 2 tables Students & Grades which look like this:

Students

+----------------+
|Id | Name       |
+----------------+
| 1 | Student 1  |
| 2 | Student 2  |
| 3 | Student 3  |
| 4 | Student 4  |
| 5 | Student 5  |
+----------------+

Grades

+-------------------+
|StudentId  | Grade |
+-------------------+
|     1     |   A   |
|     2     |   B   |
|     3     |   C   |
|     4     |   A   |
|     5     |   B   |
+-------------------+

I want to write a method which takes studentId and return his grade and percent of his grades.

Example:

  • Input: 1; returns A, 40%; // 40% since there are 2 students with Grade A
  • Input: 3; returns C, 20%; // 20% since there is only 1 student with Grade C

How can this be done in Entity Framework without querying the database multiple times?



Solution 1:[1]

You can achieve that using GroupBy

var input = 1;

var output = grades.GroupBy(x => x.Grade)
                   // Creates a new anonymouls object with calculated percentage and grade
                   .Select(x => new {Percentage = Decimal.Divide(x.Count(),grades.Count())*100, x.FirstOrDefault().Grade})
                   // Filter to get only the "grade of interest" based on the StudentId
                   .FirstOrDefault(x => x.Grade == grades.FirstOrDefault(x => x.StudentId == input)?.Grade);

Console.WriteLine($"{output?.Percentage}% - {output?.Grade}");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andre.Santarosa