3

我有一个自定义方法,可以对一组数据执行一些计算:

 private int GetPercentages(int OriginalValue, int TotalValue)
        {
            var newValue = (int)Math.Round(((decimal)OriginalValue / (decimal)TotalValue) * 100);

            return newValue;
         }

我需要能够在 LINQ to Entities 查询中运行此方法:

var data = from SurveyResponseModel in db.SurveyResponseModels
                       group SurveyResponseModel by SurveyResponseModel.MemberId into resultCount
                       select new ResultsViewModel()
                       {
                           MemberId = resultCount.Key,
                           PatientFollowUpResult = db.SurveyResponseModels.Count(r => r.PatientFollowUp),
                           PatientFollowUpResultPct = GetPercentages(db.SurveyResponseModels.Count(r => r.PatientFollowUp),totalResponsesResult),
                           ChangeCodingPracticeResult = db.SurveyResponseModels.Count(r => r.ChangeCodingPractice),
  };

我需要在查询内的大约 20 行以上运行它,所以仅仅将它嵌入内联似乎不是一个好选择。我知道它需要转换成 SQL 语法,但是我还能做些什么吗?

4

1 回答 1

3

您需要创建一个计算百分比的 lambda 表达式,如下所示:

Expression<Func<int, int, int>> calcPercentage =
    (OriginalValue, TotalValue) => (int)Math.Round(((decimal)OriginalValue / (decimal)TotalValue) * 100);

并像这样使用它:

var data = from SurveyResponseModel in db.SurveyResponseModels.ToExpandable()
           group SurveyResponseModel by SurveyResponseModel.MemberId into resultCount
           select new ResultsViewModel()
           {
               MemberId = resultCount.Key,
               PatientFollowUpResult = db.SurveyResponseModels.Count(r => r.PatientFollowUp),
               PatientFollowUpResultPct = calcPercentage.Invoke(db.SurveyResponseModels.Count(r => r.PatientFollowUp), totalResponsesResult),
               ChangeCodingPracticeResult = db.SurveyResponseModels.Count(r => r.ChangeCodingPractice),
           };

有关在 LINQ 查询中调用函数的更多信息,请点击此处

于 2012-06-22T23:58:52.437 回答