132

私は持っている:

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」になってほしい。

どうすればこれを達成できますか?

4

12 に答える 12

300

Datatable にデータが入力された後は、DataType を変更できません。ただし、以下に示すように、データ テーブルを複製し、列の型を変更して、以前のデータ テーブルから複製されたテーブルにデータをロードすることができます。

DataTable dtCloned = dt.Clone();
dtCloned.Columns[0].DataType = typeof(Int32);
foreach (DataRow row in dt.Rows) 
{
    dtCloned.ImportRow(row);
}
于 2012-01-27T01:56:49.287 に答える
33

が入力された後に列の型を変更できないのは事実ですが、DataTableを呼び出した後、 を呼び出すFillSchema前に変更できますFill。たとえば、3 番目の列が から に変換したい列だとするとdouble、次のInt32ように使用できます。

adapter.FillSchema(table, SchemaType.Source);
table.Columns[2].DataType = typeof (Int32);
adapter.Fill(table);
于 2012-01-27T02:04:11.963 に答える
12

少し違うアプローチをとってきました。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;
        }
    
于 2016-02-15T23:43:39.627 に答える
10

戻り値の型を変更することも検討してください。

select cast(columnName as int) columnName from table
于 2013-07-02T19:49:53.567 に答える
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)
于 2014-08-27T23:40:18.097 に答える
5

列のみを変更する場合は、たとえば string から int32 に Expression プロパティを使用できます。

DataColumn col = new DataColumn("col_int" , typeof(int));
table.Columns.Add(col);
col.Expression = "table_exist_col_string"; // digit string convert to int  
于 2015-09-21T07:30:10.130 に答える
4

が入力されるDataTableと、列のタイプを変更することはできません。

このシナリオでの最良のオプションは、入力する前にInt32列を追加することです。DataTable

dataTable = new DataTable("Contact");
dataColumn = new DataColumn("Id");
dataColumn.DataType = typeof(Int32);
dataTable.Columns.Add(dataColumn);

次に、元のテーブルから新しいテーブルにデータを複製できます。

DataTable dataTableClone = dataTable.Clone();

詳細については、こちらの投稿をご覧ください

于 2012-01-27T01:56:29.777 に答える
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;  
    });
}

上記のコードは、すべての 10 進数の列を double に変更します。

于 2016-10-12T22:28:57.543 に答える
1
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" );
于 2017-06-08T10:14:49.687 に答える