c# - 如何使用 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());
我怎样才能确保它是?
解决方案
发生了什么
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
推荐阅读
- perl - sed 或 Perl 一行 + 如何仅在完全匹配时替换文件中的路径
- laravel - Laravel:订购 hasManyThrough
- django - Django 站点:如何更快地使用 Databse 加载站点页面
- c# - C# ChromeDriver 代理未设置
- python - 如何使 True Check Forever
- reactjs - 如何获取rowFields以比较枢轴网格devextreme中的两列反应js
- ios - PDF 与 Swift 的交互
- c++ - 如何在 UI 中编辑/更新 dataGridView 内容并使用 C++ winforms 将它们传递给 SQL 工作台?
- azure - Azure 中默认不加载默认招摇索引页面
- ios - 如何将选定的 tableview 行存储在数组中?