Infost Infost - 3 months ago 13
C# Question

Missing Columns from Datatable once Grouped C# ODBC Datatable Console App

I have a datatable named completeDT_units
I group the coulumn "Account#" and sum "Cur-Balance...."

The grp is copied to a new data table.
How do i modify the below code to also copy over "Description" that is not copied over in the below code.

Thanks

//GROUP FOR COUNTS
var accountGroups = completeDT_units.AsEnumerable()
.GroupBy(row => row.Field<String>("Account#"))
.Select(grp => new { Account = grp.Key, Count = grp.Sum(row => row.Field<int>("Cur-Balance....")) });


var tblAccCounts = new DataTable();
tblAccCounts.Columns.Add("Account#");
tblAccCounts.Columns.Add("Cur-Balance....");
foreach (var grp in accountGroups)
tblAccCounts.Rows.Add(grp.Account, grp.Count);

Answer

You can use new keyword and add description to grouping

var accountGroups = completeDT_units.AsEnumerable()
    .GroupBy(x => new { row => row.Field<String>("Account#"), 
                        Description = row.Field<string>("Description").ToString() })
    .Select(grp => new { Account = grp.Key.row,
                         descrpt = grp.Key.Description, 
                         Count = grp.Sum(row => row.Field<int>("Cur-Balance....")) });