Reputation: 1697
I have DataTable object (OutputDT1
), I want to use LINQ to group by column ConfirmedBy
, then convert it back to a DataTable
object which has only two columns ConfirmBy
and Count
.
var result = from row in OutputDT1.AsEnumerable()
group row by new
{
ConfirmedBy = row.Field<string>("ConfirmedBy")
}
into grp
select new
{
ConfirmedBy = grp.Key.ConfirmedBy,
Count = grp.Count(),
};
Upvotes: 0
Views: 9192
Reputation: 203847
Using the solution from How to: Implement CopyToDataTable<T> Where the Generic Type T Is Not a DataRow
we can write:
var result = (from row in OutputDT1.AsEnumerable()
group row by row.Field<string>("ConfirmedBy") into grp
select new
{
ConfirmedBy = grp.Key,
Count = grp.Count(),
}).CopyToDataTable();
Upvotes: 1
Reputation: 223422
A simple way would be:
DataTable dt = new DataTable();
foreach(var item in result)
{
dt.Rows.Add(item.ConfirmedBy, item.count);
}
Upvotes: 1