J - C Sharper
J - C Sharper

Reputation: 1697

How to convert this LINQ Query result back to DataTable object?

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

Answers (2)

Servy
Servy

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

Habib
Habib

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

Related Questions