Infost Infost - 1 year ago 112
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.


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();
foreach (var grp in accountGroups)
tblAccCounts.Rows.Add(grp.Account, grp.Count);

Answer Source

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....")) });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download