如何更改DataTable中DataColumn的DataType?

时间:2012-01-27 01:49:47

标签: c# types datatable datacolumn

我有:

DataTable Table = new DataTable;
SqlConnection = new System.Data.SqlClient.SqlConnection("Data Source=" + ServerName + ";Initial Catalog=" + DatabaseName + ";Integrated Security=SSPI; Connect Timeout=120");

SqlDataAdapter adapter = new SqlDataAdapter("Select * from " + TableName, Connection);
adapter.FillSchema(Table, SchemaType.Source);
adapter.Fill(Table);

DataColumn column = DataTable.Columns[0];

我想做的是:

假设当前 column.DataType.Name “Double”。我希望它成为“Int32”

我如何实现这一目标?

12 个答案:

答案 0 :(得分:246)

在Datatable填充数据后,您无法更改DataType。但是,您可以克隆数据表,更改列类型并将数据从以前的数据表加载到克隆表,如下所示。

DataTable dtCloned = dt.Clone();
dtCloned.Columns[0].DataType = typeof(Int32);
foreach (DataRow row in dt.Rows) 
{
    dtCloned.ImportRow(row);
}

答案 1 :(得分:26)

虽然在DataTable填写后您无法更改列的类型,但您可以在致电FillSchema之后,但在致电Fill之前更改该类型。例如,假设第3列是您要从double转换为Int32的列,您可以使用:

adapter.FillSchema(table, SchemaType.Source);
table.Columns[2].DataType = typeof (Int32);
adapter.Fill(table);

答案 2 :(得分:13)

旧帖子,但我认为我已经权衡了一个DataTable扩展,它可以一次将一个列转换为给定类型:

public static class DataTableExt
{
    public static void ConvertColumnType(this DataTable dt, string columnName, Type newType)
    {
        using (DataColumn dc = new DataColumn(columnName + "_new", newType))
        {
            // Add the new column which has the new type, and move it to the ordinal of the old column
            int ordinal = dt.Columns[columnName].Ordinal;
            dt.Columns.Add(dc);
            dc.SetOrdinal(ordinal);

            // Get and convert the values of the old column, and insert them into the new
            foreach (DataRow dr in dt.Rows)
                dr[dc.ColumnName] = Convert.ChangeType(dr[columnName], newType);

            // Remove the old column
            dt.Columns.Remove(columnName);

            // Give the new column the old column's name
            dc.ColumnName = columnName;
        }
    }
}

然后可以这样调用:

MyTable.ConvertColumnType("MyColumnName", typeof(int));

当然使用您想要的任何类型,只要列中的每个值都可以实际转换为新类型。

答案 3 :(得分:8)

考虑改变返回类型:

select cast(columnName as int) columnName from table

答案 4 :(得分:8)

Dim tblReady1 As DataTable = tblReady.Clone()

'' convert all the columns type to String 
For Each col As DataColumn In tblReady1.Columns
  col.DataType = GetType(String)
Next

tblReady1.Load(tblReady.CreateDataReader)

答案 5 :(得分:8)

我采取了一些不同的方法。 我需要从OA日期格式的excel导入中解析日期时间。这种方法很简单,可以从......本质上构建,

  1. 添加您想要的类型列
  2. 翻录转换值的行
  3. 删除原始列并重命名为新列以匹配旧

    private void ChangeColumnType(System.Data.DataTable dt, string p, Type type){
            dt.Columns.Add(p + "_new", type);
            foreach (System.Data.DataRow dr in dt.Rows)
            {   // Will need switch Case for others if Date is not the only one.
                dr[p + "_new"] =DateTime.FromOADate(double.Parse(dr[p].ToString())); // dr[p].ToString();
            }
            dt.Columns.Remove(p);
            dt.Columns[p + "_new"].ColumnName = p;
        }
    

答案 6 :(得分:4)

填写DataTable后,您无法更改列的类型。

此方案中的最佳选择是在填充Int32之前向DataTable添加dataTable = new DataTable("Contact"); dataColumn = new DataColumn("Id"); dataColumn.DataType = typeof(Int32); dataTable.Columns.Add(dataColumn); 列:

DataTable dataTableClone = dataTable.Clone();

然后,您可以将原始表中的数据克隆到新表中:

{{1}}

这是一个post with more details

答案 7 :(得分:3)

如果你只想改变一个列。例如从string到int32你可以使用表达式。

DataColumn col = new DataColumn("col_int" , typeof(int));
table.columns.Add(col)
col.Expression = "table_exist_col_string"; // digit string convert to int  

答案 8 :(得分:2)

我创建了一个扩展函数,允许更改DataTable的列类型。它不是克隆整个表并导入所有数据而只是克隆列,而是解析值,然后删除原始数据。

    /// <summary>
    /// Changes the datatype of a column. More specifically it creates a new one and transfers the data to it
    /// </summary>
    /// <param name="column">The source column</param>
    /// <param name="type">The target type</param>
    /// <param name="parser">A lambda function for converting the value</param>
    public static void ChangeType(this DataColumn column, Type type, Func<object, object> parser)
    {
        //no table? just switch the type
        if (column.Table == null)
        {
            column.DataType = type;
            return;
        }

        //clone our table
        DataTable clonedtable = column.Table.Clone();

        //get our cloned column
        DataColumn clonedcolumn = clonedtable.Columns[column.ColumnName];

        //remove from our cloned table
        clonedtable.Columns.Remove(clonedcolumn);

        //change the data type
        clonedcolumn.DataType = type;

        //change our name
        clonedcolumn.ColumnName = Guid.NewGuid().ToString();

        //add our cloned column
        column.Table.Columns.Add(clonedcolumn);

        //interpret our rows
        foreach (DataRow drRow in column.Table.Rows)
        {
            drRow[clonedcolumn] = parser(drRow[column]);
        }

        //remove our original column
        column.Table.Columns.Remove(column);

        //change our name
        clonedcolumn.ColumnName = column.ColumnName;
    }
}

您可以像这样使用它:

List<DataColumn> lsColumns = dtData.Columns
    .Cast<DataColumn>()
    .Where(i => i.DataType == typeof(decimal))
    .ToList()

//loop through each of our decimal columns
foreach(DataColumn column in lsColumns)
{
    //change to double
    column.ChangeType(typeof(double),(value) =>
    {
        double output = 0;
        double.TryParse(value.ToString(), out output);
        return output;  
    });
}

上面的代码将所有十进制列更改为双精度。

答案 9 :(得分:0)

DataTable DT = ...
// Rename column to OLD:
DT.Columns["ID"].ColumnName = "ID_OLD";
// Add column with new type:
DT.Columns.Add( "ID", typeof(int) );
// copy data from old column to new column with new type:
foreach( DataRow DR in DT.Rows )
{ DR["ID"] = Convert.ToInt32( DR["ID_OLD"] ); }
// remove "OLD" column
DT.Columns.Remove( "ID_OLD" );

答案 10 :(得分:0)

我结合了Mark解决方案的效率-因此,我不必.Clone整个数据表-具有泛型和可扩展性,因此我可以定义自己的转换函数< / strong>。这就是我最终得到的:

/// <summary>
///     Converts a column in a DataTable to another type using a user-defined converter function.
/// </summary>
/// <param name="dt">The source table.</param>
/// <param name="columnName">The name of the column to convert.</param>
/// <param name="valueConverter">Converter function that converts existing values to the new type.</param>
/// <typeparam name="TTargetType">The target column type.</typeparam>
public static void ConvertColumnTypeTo<TTargetType>(this DataTable dt, string columnName, Func<object, TTargetType> valueConverter)
{
    var newType = typeof(TTargetType);

    DataColumn dc = new DataColumn(columnName + "_new", newType);

    // Add the new column which has the new type, and move it to the ordinal of the old column
    int ordinal = dt.Columns[columnName].Ordinal;
    dt.Columns.Add(dc);
    dc.SetOrdinal(ordinal);

    // Get and convert the values of the old column, and insert them into the new
    foreach (DataRow dr in dt.Rows)
    {
        dr[dc.ColumnName] = valueConverter(dr[columnName]);
    }

    // Remove the old column
    dt.Columns.Remove(columnName);

    // Give the new column the old column's name
    dc.ColumnName = columnName;
}

这样,用法就更简单了,而且还可以自定义:

DataTable someDt = CreateSomeDataTable();
// Assume ColumnName is an int column which we want to convert to a string one.
someDt.ConvertColumnTypeTo<string>('ColumnName', raw => raw.ToString());

答案 11 :(得分:0)

前足的agregar乌塔柱,前路的卢戈·科皮亚·洛斯·达托斯和埃利米纳拉

TB.Columns.Add("columna1", GetType(Integer))    
TB.Select("id=id").ToList().ForEach(Sub(row) row("columna1") = row("columna2"))    
TB.Columns.Remove("columna2")