DataTable.Copy () or DeepClone. Which one to choose?

I have a confusion

Scenario:

I want to create a copy of a DataTable to add to another DataSet. There are two ways to do this (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); } } 

My confusion:

  • Are there any other ways to do this?
  • Which one is better and why?
  • Does DataTable.Copy() DeepClone or any other logic?
+6
source share
2 answers

If I'm missing something trivial, why can't you do something like

 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); 

Little helper

 public static class Utils { public static bool IsAny<T>(this IEnumerable<T> data) { return data != null && data.Any(); } } 
+3
source

DataTable.Copy () itself creates a deep copy of the data, I'm not talking about the implementation of DataTable.Copy (), but the way to copy the copied data table is the same as if the data is copied using DeepClone , i.e. Changes made to the data in one table do not affect the others.

So in your case you can just use: -

 DataTable dtCopy = dt.Copy(); 

OR you can also use: -

 DataTable dtCopy = dt.Clone(); dtCopy.Merge(dt); 
0
source

Source: https://habr.com/ru/post/927003/


All Articles