Reputation: 123
I have two datatables with identical schemas, business partners and addresses. I'm trying to combine them in a specific format in order to import into another system.
Basically, I want the output to be as follows:
Here is the latest code I'm trying:
var finalDt = BpDt.Clone();
foreach(DataRow BpRow in BpDt.Rows)
{
finalDt.ImportRow(BpRow);
foreach(DataRow AddressRow in AddressDt.Rows)
{
if(Convert.ToString(BpRow["id"]).Equals(Convert.ToString(BpRow["id"])))
finalDt.ImportRow(AddressRow);
}
}
It seems to get caught in a infinite loop but I don't understand why. Is there a better way to approach this?
Upvotes: 2
Views: 40
Reputation: 6731
Your approach to this is terrible. But if you insist on going down this road, this should work:
var finalDt = BpDt.Clone();
foreach(DataRow BpRow in BpDt.Rows)
{
finalDt.ImportRow(BpRow);
foreach(DataRow AddressRow in AddressDt.Rows)
{
if(Convert.ToString(BpRow["id"]).Equals(Convert.ToString(AddressRow["id"])))
finalDt.ImportRow(AddressRow);
}
}
Upvotes: 1
Reputation: 332
it seems like...
if(Convert.ToString(BpRow["id"]).Equals(Convert.ToString(BpRow["id"])))
will always be true
. So you would just be inserting every AddressRow
for each BpRow
. Depending on your dataset size, this could be taking a really long time. Should the id
comparison be this?
if(Convert.ToString(AddressRow["id"]).Equals(Convert.ToString(BpRow["id"])))
Conceptually this would be similar to a join on the id
field.
A better approach might be to use LINQ. If you use the AsEnumerable()
extension for DataTable
you could query AddressDt
using LINQ...
Upvotes: 0