[英]How to calculate percentage in Entity Framework
Let's say I have 2 tables Students
& Grades
which look like this:假设我有 2 个表格
Students
& Grades
,如下所示:
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.我想编写一个方法,它采用
studentId
并返回他的成绩和他的成绩百分比。
Example:例子:
How can this be done in Entity Framework without querying the database multiple times?如何在不多次查询数据库的情况下在实体框架中完成此操作?
You can achieve that using GroupBy
您可以使用
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}");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.