Search code examples
c#linqdatatablegroup-bylinq-to-dataset

How to get the summation in group by statement linq query


I have the following LINQ query :

var groupedData = from b in loans.AsEnumerable()                     
                  group b by b.Field<int>("loan_code") & b.Field<int>("emp_num")
                  into f        
                  select f.CopyToDataTable();

I want to select f and in addition to that the summation of Tot field and copy the result in data table .how to do that?


Solution

  • Get required data

    var groupedData = from r in loans.AsEnumerable()                     
                      group r by new { 
                          LoanCode = r.Field<int>("loan_code"),
                          EmpNum = r.Field<int>("emp_num") 
                      } into g
                      select new {
                          g.Key.LoanCode,
                          g.Key.EmpNum,
                          Tot = g.Sum(r => r.Field<int>("Tot")) // assume integer
                      };
    

    Then use custom CopyToDataTable method (which works for types that don't implement DataRow) to convert them to DataTable. Or you can build DataTable manually:

    DataTable dt = new DataTable();
    dt.Columns.Add("loan_code", typeof(int));
    dt.Columns.Add("emp_num", typeof(int));
    dt.Columns.Add("Tot", typeof(int));
    
    foreach(var data in groupedData)
        dt.Rows.Add(data.LoanCode, data.EmpNum, data.Tot);