简体   繁体   English

如何在实体框架中计算百分比

[英]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:例子:

  • Input: 1;输入:1; returns A, 40%;回报 A,40%; // 40% since there are 2 students with Grade A // 40%,因为有 2 名学生成绩 A
  • Input: 3;输入:3; returns C, 20%;返回 C,20%; // 20% since there is only 1 student with Grade C // 20% 因为只有 1 名学生成绩为 C

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM