Sujeet Raman

Sujeet Raman

  • 796
  • 915
  • 333.3k

how to edit data table column header names using c#?

Sep 15 2020 7:22 AM
I have some logical block in my c# program,as i am new to c# programming.
i have a data-table with duplicate header column names .I have to change my duplicate header like concatenate the name of the prior column to make these headers unique.Table names are coming dynamically.
Current datatable
ID |Name|Age| School | Name | state| Part| Country|Division|Part
Expecting
ID |Name|Age| School | Name+school | state| Part| Country|Division|Part+Division
what i have tried and blocked here below
public DataTable RemoveDuplicateRows(DataTable dTable)
{
string[] columnNames = dTable.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
for (int i = 0; i < columnNames.Length; i++)
{
columnNames[i] = columnNames[i].Split('.')[0].Trim();
}
for (int i = 0; i < columnNames.Length; i++)
{
//create nested loop for compare current values with actual value of arr
for (int j = i + 1; j < columnNames.Length; j++)
{
if (columnNames[i] == columnNames[j])
{
var previous = columnNames[i - 1];
var current = columnNames[i];
columnNames[i] = current + previous;
//blocked here
//only one header is concatenating
//how can i add this newly edited columns to my datatable
}
}
}
return dTable; //cant get updated coloumn headers
}

Answers (7)