3

I have to convert my given linq query in lambda expression. i.e.

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);
Amir Sherafatian
  • 2,083
  • 2
  • 20
  • 32
user1078749
  • 263
  • 2
  • 3
  • 7
  • 2
    So what have you tried, and what went wrong? Grouping by more than two columns is exactly the same as grouping by two columns. Why do you need to convert the query out of query expression form though? If your query is more readable as a query expression, why not keep it that way? – Jon Skeet Feb 28 '14 at 07:58
  • 1
    Do you really have to? If you need to build eg. the `where` dynamically, you can do that with the extension methods, and then apply the rest of the transformation through LINQ keywords as usual. I assume that your issue is caused by the anonymous grouping type. You can also always create your own type to hold the keys. – Luaan Feb 28 '14 at 07:59

2 Answers2

17

this is your 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();
Amir Sherafatian
  • 2,083
  • 2
  • 20
  • 32
7

Well I don't think I should do all your work for you but specifically the group by you are asking about could be done like:

...GroupBy(x => new { x.ID, x.FirstName, x.LastName })...
Ashley Medway
  • 7,151
  • 7
  • 49
  • 71