LINQ 查询中的对象初始值设定项 - 是否可以重用计算数据?
我正在使用一个 linq 查询,它看起来(经过一些简化)如下所示:
List<UserExams> listUserExams = GetUserExams();
var examData =
from userExam in listUserExams
group by userExam.ExamID into groupExams
select new ExamData()
{
ExamID = groupExams.Key,
AverageGrade = groupExams.Average(e => e.Grade),
PassedUsersNum = groupExams.Count(e => /* Some long and complicated calculation */),
CompletionRate = 100 * groupExams.Count(e => /* The same long and complicated calculation */) / TotalUsersNum
};
令我困扰的是出现两次的计算表达式,即 PassedUsersNum 和 CompletionRate。
假设CompletionRate = (PassedUsersNum / TotalUsersNum) * 100,如何通过重用PassedUsersNum的计算来编写它,而不是再次编写该表达式?
I'm using a linq query which looks (after some simplification) something like the following:
List<UserExams> listUserExams = GetUserExams();
var examData =
from userExam in listUserExams
group by userExam.ExamID into groupExams
select new ExamData()
{
ExamID = groupExams.Key,
AverageGrade = groupExams.Average(e => e.Grade),
PassedUsersNum = groupExams.Count(e => /* Some long and complicated calculation */),
CompletionRate = 100 * groupExams.Count(e => /* The same long and complicated calculation */) / TotalUsersNum
};
What bothers me is the calculation expression which appears twice, for PassedUsersNum and CompletionRate.
Assuming that CompletionRate = (PassedUsersNum / TotalUsersNum) * 100
, how can I write it by reusing the calculation of PassedUsersNum, instead of writing that expression again?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的方法是首先使用
let
注入另一个选择步骤:当然,每个组只会对表达式求值一次。
The simplest way would be to use
let
to inject another selection step first:The expression will only be evaluated once per group, of course.
您还可以将 Count 函数提取到另一个返回 Func 的方法中(如果需要),或者采用 double 并返回 bool 的方法。
You can also just extract your Count func into another method which returns a Func if you want, or a method that takes a double and returns a bool.