Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy C# DataTable and convert all values to string

I have a DataTable with columns of different types. What I want is a DataTable that has the same column names but all values are strings. That is, if this is the first:

Name   Age
-----------
John   31
Alice  27
Marge  45

where Name is a String column and Age is an Int32 column, what I want is:

Name   Age
-----------
John   31
Alice  27
Marge  45

where Name and Age are both string columns. The output table must contain the same values as the input table but every value must be converted to a string. Can anyone provide any insight on how one might go about doing this? I thought about maybe doing something like

foreach (DataColumn col in inputTable.Columns)
{
    outputTable.Columns.Add(col.ColumnName, typeof(string));

    foreach (DataRow row in inputTable.Rows)
    {
        ...??
    }
}

Or perhaps there is a better or more efficient approach? Any guidance would be greatly appreciated.

like image 669
Alex A. Avatar asked Apr 09 '14 17:04

Alex A.


1 Answers

You can't modify a column type in DataTable if already has records. You can Clone DataTable and then modify column type in each column of cloned table. Later you can import rows.

DataTable dtClone = dt.Clone(); //just copy structure, no data
for (int i = 0; i < dtClone.Columns.Count; i++)
{
    if (dtClone.Columns[i].DataType != typeof(string))
        dtClone.Columns[i].DataType = typeof(string);
}

foreach (DataRow dr in dt.Rows)
{
    dtClone.ImportRow(dr);
}

dtClone will have every column as of string and all the data from original table dt

like image 66
Habib Avatar answered Nov 14 '22 23:11

Habib