Group By Sum Linq to SQL in C#

前端 未结 1 650
死守一世寂寞
死守一世寂寞 2021-02-05 11:31

Really stuck with Linq to SQL grouping and summing, have searched everywhere but I don\'t understand enough to apply other solutions to my own.

I have a view in my datab

1条回答
  •  失恋的感觉
    2021-02-05 11:50

    Start out by defining a class to hold the result:

    public class GroupedRow
    {
      public string UserDescription {get;set;}
      public string ProjectDescription {get;set;}
      public double SumOfHoursBetweenToAndFromDate {get;set;}
    }
    

    Since you've already applied filtering, the only thing left to do is group.

    List result =
    (
      from row in source
      group row by new { row.UserDescription, row.ProjectDescription } into g
      select new GroupedRow()
      {
        UserDescription = g.Key.UserDescription,
        ProjectDescription = g.Key.ProjectDescription,
        SumOfHoursBetweenToAndFromDate = g.Sum(x => x.Hours)
      }
    ).ToList();
    

    (or the other syntax)

    List result = source
      .GroupBy(row => new {row.UserDescription, row.ProjectDescription })
      .Select(g => new GroupedRow()
      {
        UserDescription = g.Key.UserDescription,
        ProjectDescription = g.Key.ProjectDescription,
        SumOfHoursBetweenToAndFromDate = g.Sum(x => x.Hours)
      })
      .ToList();
    

    0 讨论(0)
提交回复
热议问题