Best way to copy Data from one DataTable to another DataTable with diffrent structure

时光怂恿深爱的人放手 提交于 2019-12-31 06:56:08

问题


I am copying data from DataTable to another DataTable with a structure. I have to hardcode columns number in the loop and copy the data in object array.

What will be the best way to achieve it ?

IEnumerable<DataRow> query = from vendInv in VendorInvoiceStagingTable.AsEnumerable()
                             where vendInv.Field<string>(VendInvoice.Number) == InvoiceHeader
                             select vendInv;

Object[] obj = new Object[10];
var item = query.First();

for (int idx = 0; idx < 10; idx++)
{
    obj[idx] = item[idx];
}

VendorInvoiceTable.Rows.Add(obj);

回答1:


I'm not 100% sure why you want to copy the data to an array before putting it into the VendorInvoiceTable, but either way:

IEnumerable<DataRow> query = from vendInv in VendorInvoiceStagingTable.AsEnumerable()
                             where vendInv.Field<string>(VendInvoice.Number) == InvoiceHeader
                             select vendInv;

// Would this be ok?
VendorInvoiceTable.Rows.Add(query.First().ItemArray);

// ...or if not, how about this?
object[] sourceData = query.First().ItemArray;
object[] targetData = new object[sourceData.Length];
sourceData.CopyTo(targetData, 0);
VendorInvoiceTable.Rows.Add(targetData);



回答2:


Probably, check out Adapter pattern, it will allow you to adapt the structure of one data table to another. A simple explanation and sample code can be found at Dofactory.



来源:https://stackoverflow.com/questions/5763811/best-way-to-copy-data-from-one-datatable-to-another-datatable-with-diffrent-stru

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!