How can I convert a DataRow array to a DataTable without iteration?
How can I convert a DataRow array to a DataTable without iteration?开发者_开发百科
You can use:
dataTable = datarowarray.CopyToDataTable()
but ensure that datarowarray
has length > 1
, otherwise it will end up with unwanted exceptions.
I dont think you can put an array of datarows to a datatable. You can import one row at a time using DataTable.ImportRow.
foreach(DataRow row in dataRowArray)
{
dataTable.ImportRow(row);
}
Even if there did exist a .NET framework function like
myDataTable.LoadRows(dataRowArray)
... all that would do is hide the iteration. The framework doesn't magically circumvent the iterative step (though in some cases it might be doing something gee-whiz smart to optimize it).
Recommend to use some bulk function of .NET framework for better performance.
DataTable dtDestination = new DataTable(); //your destination datatable
DataRow[] row;
row = dtMain.Select($"unit IN ({ filterString })"); //select data from main datatable
if (row.Length == 0)
{
//handle if nothing match your select statment.
}
else
{
//if have found row.
dtDestination = row.CopyToDataTable();
//or if your datatable is in DataSet and it's readonly.
DataTable dtTemp = row.CopyToDataTable();
dts.Tables["labofpatient"].Merge(dtTemp);
}
This is another way to import by loop, but it's slower and take time more than above function.
DataTable dtDestination = new DataTable(); //your destination datatable
DataRow[] row;
row = dtMain.Select($"unit IN ({ filterString })"); //select data from main datatable
foreach (DataRow dr in row)
{
//you can choose one of the line of code below. It work on the same and no different in performance.
dtDestination.Rows.Add(dr.ItemArray);
dtDestination.ImportRow(dr);
}
or by iterate value in datatable
DataTable dtDestination = new DataTable(); //your destination datatable
for(int i = 0; i < dt.Rows.count; i++)
{
dtDestination.Rows.Add(dt.Rows[i]["col1"].ToString(), dt.Rows[i]["col2"].ToString());
}
DataTable dt = new DataTable();
DataRow[] dataRowArray = dt.Select("");
DataTable dataTable = new DataTable();
foreach (DataRow row in dataRowArray)
{
dataTable = dataTable.Clone();
dataTable.ImportRow(row);
}
精彩评论