How can we copy the column data of one DataTable to another, even if there are different column names between DataTables?

两盒软妹~` 提交于 2019-12-22 09:41:28

问题


I have two DataTables. First is

DataTable NameAddressPhones = new DataTable(); 

with Three columns Name, Address and PhoneNo.But I only want two columns Name and Address data so I want to copy those columns (with data) to the new DataTable.

DataTable NameAddress = new DataTable(); 

For that I do

            foreach (DataRow sourcerow in NameAddressPhones.Rows)
            {
                DataRow destRow = NameAddress.NewRow();
                foreach (string colname in columns)
                {
                    destRow[colname] = sourcerow[colname];
                }
                NameAddress.Rows.Add(destRow);
            }

I clear the NameAddressPhones(first) DataTable every time there are new records inserted in the table. And every time there will be the same number of columns but the column names will be different like Nm instead of Name, Add instead of Address.Now the problem is the second DataTable already has column names Name and Address and now I want to copy the columns data of Nm and Add to the second DataTable but the column names are different than the column names of the second DataTable. So even if there are different column names I want to copy Nm column data of first DataTable to the column Name of second DataTable and column Add data of first DataTable to column Address of second DataTable.

In short how can we copy column data from one DataTable to another even if there are different column names of both DataTables like Nm is the column name of first DataTable and Name is the column name of second DataTable then the data of the column Nm should be copied to the column Name.


回答1:


Here's the simplest way:

foreach (DataRow sourcerow in NameAdressPhones.Rows)
{
    DataRow destRow = NameAdress.NewRow();
    destRow["Name"] = sourcerow["Nm"];
    destRow["Address"] = sourcerow["Add"];
    NameAdress.Rows.Add(destRow);
}

Automation is great when it's available. When it's not, you have to map source columns to destination columns in some manner.

If the columns are in the same order in both tables, you could just reference the values by ordinal instead of column name, but that's such a bad idea I'm not even going to post any code for it.




回答2:


Use column index number rather than names:

destRow[0] = sourcerow[0]; // for column 0 = "Name" or "NM"



回答3:


If I've understood your question right, then the way this is usually done is by using stored procedures. You have the same stored procedures in both databases, but the implementation is specific to the table schema of each database. This allows you the abstraction you need.



来源:https://stackoverflow.com/questions/2592637/how-can-we-copy-the-column-data-of-one-datatable-to-another-even-if-there-are-d

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