2013-02-18 125 views
1

我试图找出如何做到这一点,但仍然与Linq sytax混淆。group by select max in linq

我的目的是寻找最大EFFECTIVEDATE与指定empCode

var x = (from workingResult in this.DataWorkspace.ApplicationData.WorkingResults 
     group workingResult by workingResult.EmployeeCode into g 
     where g.EmployeeCode == employeeCode 
     && (g.EffectiveDate.HasValue 
     && g.EffectiveDate.Value.Equals(date)) 
     select new {EffectiveDate = g.Max(d=>d.EffectiveDate)}); 

但是编译器显示我这个

“找不到源类型的查询模式的实现” ... '。'GroupBy'找不到,请考虑明确指定范围变量'workingResult'的类型。“

这是什么意思?我真的很需要你的帮助。 谢谢。

+0

'this.DataWorkspace.ApplicationData.WorkingResults'是什么类型? – 2013-02-18 08:39:48

回答

1

您的代码存在的问题是您将组g视为单个workingResult。实际上它是它们的一个列表。此外,g.EffectiveDate.Value.Equals(date)的目的是什么?如果不存在与date变量匹配的生效日期,则会导致最大生效日期始终为date或不生效。

下面应该工作:

DataWorkspace.ApplicationData.WorkingResults 
      .Where(x => x.EmployeeCode == employeeCode) 
      .Max(x => x.EffectiveDate); 

这将返回指定的employeeCode最大EffectiveDate

1

该行where g.EmployeeCode == employeeCode无效。 g类型为IEnumerable<IGrouping<_EmployeeCode type_, _Working result type_>>。请尝试以下操作:

var x = from g2 in (from workingResult in this.DataWorkspace.ApplicationData.WorkingResults 
        group workingResult by workingResult.EmployeeCode into g 
        select g) 
     select new {EmployeeCode = g2.Select(w => w.EmployeeCode), MaxEffectiveDate = g2.Max(w => w.EffectiveDate)}; 

现在x包含最大EffectiveDateIEnumerable<_EmployeeCode type_, _Effective data type_>每个EmployeeCode