Reputation: 130
I am reading a ".xml" file from which I will be creating a Data Table. The columns of the Data Table depends on the ".xml" file. Below is the example. enter image description here
As shown the example, data1, data2, data3... etc will be fetched from .xml file. Data(a,b,c,d,as,asd.. etc) is added with respect to Column headers(item1,item2,item3... etc).
I want to merge columns with respect to content of a row. i.e. data1 of first column(item1) should be merged with data1 of 4th column(item4) and 4th column should be deleted. Is it possible?
Below is the expected output: enter image description here
Upvotes: 0
Views: 15997
Reputation: 11
public DataTable CombileDataTable(DataTable dt1, DataTable dt2)
{
DataTable dtNew = new DataTable();
foreach (DataColumn col in dt1.Columns)
{
dtNew.Columns.Add(col.ColumnName);
}
foreach (DataColumn col in dt2.Columns)
{
dtNew.Columns.Add(col.ColumnName);
}
for(int i=0; i<dt1.Rows.Count; i++)
{
DataRow item = dtNew.NewRow();
foreach (DataColumn col in dt1.Columns)
{
item[col.ColumnName] = dt1.Rows[i][col.ColumnName];
}
foreach (DataColumn col in dt2.Columns)
{
item[col.ColumnName] = dt2.Rows[i][col.ColumnName];
}
dtNew.Rows.Add(item);
dtNew.AcceptChanges();
}
return dtNew;
}
Upvotes: 1
Reputation: 184
Please do this:
static DataTable GetTable()
{
// Here we create a DataTable with four columns.
DataTable table = new DataTable();
table.Columns.Add("Item1", typeof(string));
table.Columns.Add("Item2", typeof(string));
table.Columns.Add("Item3", typeof(string));
table.Columns.Add("Item4", typeof(string));
// Here we add five DataRows.
table.Rows.Add("a", "as", "asd", "");
table.Rows.Add("b", "asd", "asd", "");
table.Rows.Add("c", "a", "asd", "");
table.Rows.Add("d", "a", "asd", "");
table.Rows.Add("", "", "", "a");
table.Rows.Add("", "", "", "d");
table.Rows.Add("", "", "", "asd");
return table;
}
DataTable dt = GetTable();
foreach (DataRow dr in dt.Rows)
{
if (!String.IsNullOrEmpty(dr["Item4"].ToString()) && String.IsNullOrEmpty(dr["Item1"].ToString()))
{
dr["Item1"] = dr["Item4"].ToString(); //assign value of column 4 to column1
}
}
dt.Columns.Remove("Item4"); //delete column 4
Upvotes: 2