简体   繁体   中英

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(),
             };

A simple way would be:

DataTable dt = new DataTable();
foreach(var item in result)
{
  dt.Rows.Add(item.ConfirmedBy, item.count);
}

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM