列表中的linq查询和类方法中的linq查询之间的区别

时间:2014-06-24 15:51:13

标签: c# linq

我有一个自定义对象列表,我使用以下方法查询它们:

private double GetSurveyorEarliestAttendenceMIPercentage(IList<InsuranceJobDTO> jobs, int workingDays, int year, int month)
{
    var kpi = from j in jobs
    where j.EarliestSurveyDateOffered.HasValue &&
          j.EarliestSurveyDateOffered.Value.Year == year &&
          j.EarliestSurveyDateOffered.Value.Month == month &&
          (j.InstructionToEarliestSurveyDateOffered.Value <= workingDays || 
          !j.IsPolicyHolderSurveyDatePreference.Value)
    select j;

    double totalCount = kpi.Count();
    double withinSLACount = kpi.Count(x => x.InstructionToEarliestSurveyDateOffered.Value <= workingDays);

    return totalCount > 0 ? withinSLACount / totalCount : 0;
}

我决定使用更简洁的方法来生成相同的结果可能是向自定义对象添加方法:

public bool MeetsSurveyorEarliestAttendanceCriteria(int year, int month, int workingDays)
{
    return (EarliestStartDateOffered.HasValue &&
            EarliestSurveyDateOffered.Value.Year == year &&
            EarliestSurveyDateOffered.Value.Month == month &&
            (InstructionToEarliestSurveyDateOffered.Value <= workingDays || !IsPolicyHolderSurveyDatePreference.Value));
 }

将原始查询更改为以下内容:

private double GetSurveyorEarliestAttendenceMIDays(IList<InsuranceJobDTO> jobs, int workingDays, int year, int month)
{
    var kpi = from j in jobs where j.MeetsSurveyorEarliestAttendanceCriteria(year, month, workingDays) select j;                      

    double totalCount = kpi.Count();
    double totalWorkingDays = kpi.Sum(x => x.InstructionToEarliestSurveyDateOffered.Value);

    return totalCount > 0 ? totalWorkingDays / totalCount : 0;
}   

这产生了完全不同的结果,我不知道为什么?

1 个答案:

答案 0 :(得分:3)

看起来您正在计算两个不同的指标:

double withinSLACount = kpi.Count(x => x.InstructionToEarliestSurveyDateOffered.Value <= workingDays);

double totalWorkingDays = kpi.Sum(x => x.InstructionToEarliestSurveyDateOffered.Value);