Rocshy
Rocshy

Reputation: 3509

Group rows in a datatable

I am interested in grouping some rows in a datatable after 2 columns and save the results in another datatable. I have the following code for grouping the rows:

var result = from t in newtable.AsEnumerable()
               group t by new { Col1= t.Field<String>("ID1"), Col2=  t.Field<String>("ID2") } into grp
                 select new
                 {
                     Col1= grp.Key.ID1,
                     Col2= grp.Key.ID2
                 };

How can I easily convert result into a datatable?

Upvotes: 2

Views: 1266

Answers (2)

Carlos Landeras
Carlos Landeras

Reputation: 11063

Just use CopyToDatatable with your resultant query:

IEnumerable<DataRow> query = from t in newtable.AsEnumerable()
group t by new { Col1 = t.Field<String>("ID1"), Col2 = t.Field<String>("ID2") } into grp
 select new
{
Col1 = grp.Key.ID1,
Col2 = grp.Key.ID2
};
DataTable boundTable = query.CopyToDataTable<DataRow>();

CopyToDatatable is in System.Data.DataSetExtensions namespace

Upvotes: 2

Rahul
Rahul

Reputation: 5636

You have to apply foreach loop something like that

foreach (var item in results)
                {
                    Datatable dt = new DataTable();
                    DataRow dr = dt.NewRow();
                    dr["Col1"] = item.Col1;
                    dr["Col2"] = item.Col2;
                    dt.Rows.Add(dr);
                }

You have to apply this type of scenario.

Hope it works.

Upvotes: 0

Related Questions