Nik*_*wal 6 .net c# datatable clone
我有一个困惑
场景:
我想创建一个DataTable的副本,以添加到另一个DataSet.有两种方法(AFAIK):
1. Make a Copy using DataTable.Copy()
2. Make a Deep Clone using
public static T DeepClone<T>(this T source)
{
if (!typeof(T).IsSerializable)
throw new ArgumentException("The type must be serializable.", "source");
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
return default(T);
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
Run Code Online (Sandbox Code Playgroud)
我的困惑:
DataTable.Copy()在内部使用DeepClone或一些其他的逻辑是什么?DataTable.Copy()本身会创建数据表的深层副本,我不是在谈论 DataTable.Copy() 的实现,而是复制数据表的工作方式与使用DeepClone复制数据相同,即对一个表的数据不会影响另一个表。
所以在你的情况下你可以简单地使用:-
DataTable dtCopy = dt.Copy();
Run Code Online (Sandbox Code Playgroud)
或者您也可以使用:-
DataTable dtCopy = dt.Clone();
dtCopy.Merge(dt);
Run Code Online (Sandbox Code Playgroud)
除非我错过了一些微不足道的事情,否则你为什么不能做类似的事情
DataSet source = GetMySourceDataSet();
DataSet destination = new DataSet();
DataTable orders = source.Tables["SalesOrderHeader"];
// Query the SalesOrderHeader table for orders placed
// after August 8, 2001.
IEnumerable<DataRow> query =
from order in orders.AsEnumerable()
where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
select order;
// Create a table from the query.
DataTable modifiedOrders = query.IsAny() ? query.CopyToDataTable<DataRow>() : new DataTable();
destination.Tables.Add(modifiedOrders);
Run Code Online (Sandbox Code Playgroud)
小帮手
public static class Utils {
public static bool IsAny<T>(this IEnumerable<T> data) {
return data != null && data.Any();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4312 次 |
| 最近记录: |