分组通过Lambda表达式使用两列以上的列

时间:2014-02-28 07:48:45

标签: c# linq lambda

我必须在lambda表达式中转换我给定的linq查询。即。

var scholars = (from scholar in db.Scholars
                join suspension in db.Suspensions 
                    on scholar.ID equals suspension.ScholarID

                where suspension.StartDate >= startDate && 
                      suspension.EndDate <= endDate

                group scholar by new { scholar.ID, scholar.FirstName, scholar.LastName }
                    into g

                select new
                {
                    FullName = g.Key.FirstName +" " + g.Key.LastName,
                    TotalSuspensionSum = g.Sum(x => x.Suspensions.Sum(y => y.SuspensionDays))
                })
                .ToList()
                .OrderBy(x=> x.FullName);

2 个答案:

答案 0 :(得分:15)

这是你的lambda:

var scholars = db.Scholars.Join(db.Suspensions,
        scholar => scholar.ID,
        suspension => suspension.ScholarID,
        (scholar, suspension) => new {scholar, suspension})
    .Where(u => u.suspension.StartDate >= startDate && 
                u.suspension.EndDate <= endDate)
    .GroupBy(u => new { u.scholar.ID, u.scholar.FirstName, u.scholar.LastName })
    .Select(u => new 
        {
            FullName = u.Key.FirstName + " " + u.Key.LastName,
            TotalSuspensionSum = u.Sum(x => 
                x.scholar.Suspensions.Sum(y => y.SuspensionDays)
            )
        })
    .OrderBy(x => x.FullName)
    .ToList();

答案 1 :(得分:6)

嗯,我认为我不应该为你完成所有的工作,但特别是你要问的小组可以这样做:

...GroupBy(x => new { x.ID, x.FirstName, x.LastName })...