Reputation: 3406
I am trying to transfer rows from one DataTable
to many other dynamically generated DataTable
s. The parent DataTable
contains data in following format:
ID Name Type
--------------
1 ABC 0
1 PQR 2
2 XYZ 8
2 QWE 7
3 IOP 6
I want that the rows with same ID
must be in one table. For example, above scenario will generate 3 tables. One containing rows with ID = 1
, second one containing rows with ID = 2
and third one containing rows with ID = 3
. I am trying to achieve this using following code:
DataSet ResultantDataSet = new DataSet();
DataView dv = InputDataSet.Tables[0].DefaultView;
dv.Sort = "ID";
int newID = -1;
DataTable dt = null;
foreach(DataRow dr in dv.ToTable().Rows) {
if (newID != int.Parse(dr["ID"].ToString())) {
newID = int.Parse(dr["ID"].ToString());
if (dt != null) ResultantDataSet.Tables.Add(dt);
dt = new DataTable();
} else {
dt.ImportRow(dr);
}
}
But the problem is that the ResultantDataSet
contains tables with empty rows that have single unnamed column. What is going wrong?
Upvotes: 1
Views: 552
Reputation: 4204
try this.
IEnumerable<DataTable> tables =
table.AsEnumerable().GroupBy(t => t.Field<int>("ID")).Select(t => t.CopyToDataTable());
Upvotes: 3