首页 > 解决方案 > 如何使用 CopyToDataTable() 在 C# 中复制 DateTimeMode?

问题描述

我正在使用 CopyToDataTable 来选择更大表的子集。但是,“utcDT”的 DateTimeMode 不会复制到新表中:

        var x = new DataTable();
        x.Columns.Add("utcDT", typeof(System.DateTime));
        x.Columns["utcDT"].DateTimeMode = DataSetDateTime.Utc;
        x.Columns.Add("Symbol", typeof(System.String));

        var newRow = x.NewRow();
        newRow.SetField("utcDT", DateTime.Now);
        newRow.SetField("Symbol","A");
        x.Rows.Add(newRow);
        Console.WriteLine(x.Columns["utcDT"].DateTimeMode.ToString());

        var y = x.AsEnumerable().Where(s => s.Field<string>("Symbol")=="A").CopyToDataTable();
        Console.WriteLine(y.Columns["utcDT"].DateTimeMode.ToString());

我怎样才能确保它是?

标签: c#datatable

解决方案


发生了什么

CopyToDataTable只复制列的名称和类型。

参考来源

// We do not copy the same properties that DataView.ToTable does.
// If user needs that functionality, use other CopyToDataTable overloads.
// The reasoning being, the IEnumerator<DataRow> can be sourced from
// different DataTable, so we just use the "Default" instead of resolving the difference.

foreach (DataColumn column in current.Table.Columns)
{
    table.Columns.Add(column.ColumnName, column.DataType);
}

解决方案

1.AsDataView().ToTable()

使用AsDataView(请参阅使用 DataView 过滤(LINQ to DataSet)ToTable()

var z = x.AsEnumerable()
         .Where(s => s.Field<string>("Symbol") == "A")
         .AsDataView()
         .ToTable();

2 Clone().->CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption)

您可以使用Clone which '克隆 DataTable 的结构,包括所有 DataTable 模式和约束。' 后跟CopyToDataTable,但是采用目标表的一个版本。

var z = x.Clone();
x.AsEnumerable()
   .Where(s => s.Field<string>("Symbol") == "A")
   .CopyToDataTable(z,LoadOption.OverwriteChanges);

测试

(your dt definition here) 
Console.WriteLine(x.Columns["utcDT"].DateTimeMode);

var y = x.AsEnumerable()
        .Where(s => s.Field<string>("Symbol") == "A")
        .CopyToDataTable<DataRow>();
Console.WriteLine(y.Columns["utcDT"].DateTimeMode);

var z = x.AsEnumerable()
        .Where(s => s.Field<string>("Symbol") == "A")
        .AsDataView()
        .ToTable();
Console.WriteLine(z.Columns["utcDT"].DateTimeMode);

var a = x.Clone();
x.AsEnumerable()
        .Where(s => s.Field<string>("Symbol") == "A")
        .CopyToDataTable(a,LoadOption.OverwriteChanges);
Console.WriteLine(a.Columns["utcDT"].DateTimeMode);

输出

Utc
UnspecifiedLocal
Utc
Utc

推荐阅读