【发布时间】:2011-02-02 18:30:33
【问题描述】:
如何在不迭代的情况下将 DataRow 数组转换为 DataTable?
【问题讨论】:
标签: c#-2.0
如何在不迭代的情况下将 DataRow 数组转换为 DataTable?
【问题讨论】:
标签: c#-2.0
我认为您不能将一组数据行放入数据表中。您可以使用 DataTable.ImportRow 一次导入一行。
foreach(DataRow row in dataRowArray)
{
dataTable.ImportRow(row);
}
【讨论】:
即使确实存在像这样的 .NET 框架功能
myDataTable.LoadRows(dataRowArray)
...所有要做的就是隐藏迭代。该框架并没有神奇地绕过迭代步骤(尽管在某些情况下它可能会做一些聪明的事情来优化它)。
【讨论】:
你可以使用:
dataTable = datarowarray.CopyToDataTable()
但要确保datarowarray 有length > 1,否则最终会出现不需要的异常。
【讨论】:
DataTable dt = new DataTable();
DataRow[] dataRowArray = dt.Select("");
DataTable dataTable = new DataTable();
foreach (DataRow row in dataRowArray)
{
dataTable = dataTable.Clone();
dataTable.ImportRow(row);
}
【讨论】:
DataRow 数组的解决方案。您的解决方案不就是这样做的吗?
建议使用 .NET 框架的一些批量功能以获得更好的性能。
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);
}
这是另一种循环导入的方式,但比上面的功能更慢且耗时。
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);
}
或通过迭代数据表中的值
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());
}
【讨论】: