单个查询中的Group By和Max的LINQ查询

时间:2013-03-21 11:04:51

标签: c# linq

我有以下LINQ查询,但是我想修改它想要由staffId进行分组,并且只选择那些其ObservationDate为每个staffId的Max的记录。

from ob in db.TDTObservations.OfType<TDTSpeedObservation>()
select new
{
   Id = ob.ID,
   AcademicYearId = ob.Teachers.FirstOrDefault().Classes.FirstOrDefault().AcademicYearID,
   observationDate = ob.ObservationDate,
   schoolId = ob.Teachers.FirstOrDefault().Classes.FirstOrDefault().SchoolID,
   staffId=ob.Teachers.FirstOrDefault().ID
};

2 个答案:

答案 0 :(得分:1)

var observations = 
    from ob in db.TDTObservations.OfType<TDTSpeedObservation>()
    select new  {
       Id = ob.ID,
       AcademicYearId = ob.Teachers.FirstOrDefault().Classes.FirstOrDefault().AcademicYearID,
       observationDate = ob.ObservationDate,
       schoolId = ob.Teachers.FirstOrDefault().Classes.FirstOrDefault().SchoolID,
       staffId=ob.Teachers.FirstOrDefault().ID
    };

var result = from o in observations
             group o by o.staffId into g
             select g.OrderByDescending(x => x.observationDate).First();

答案 1 :(得分:0)

怎么样:特此你首先按照他们的ID将你的参赛作品(教师)分组,然后从每个小组(grp)按照最新的ObservationDate选择那个

var observations = from d in db.TDTObservations.OfType<TDTSpeedObservation>()
                   group d by d.Teachers.FirstOrDefault().ID into grp
                   select grp.OrderByDescending(g => g.ObservationDate).FirstOrDefault();