2

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:

  • Business Partner
  • All associated addresses
  • Next business partner
  • All associated addresses

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?

user2486993
  • 103
  • 10

2 Answers2

1

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);
                }
            }
Unknown Coder
  • 6,625
  • 20
  • 79
  • 129
0

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...

LINQ query on a DataTable

Community
  • 1
  • 1
temarsden
  • 332
  • 5
  • 16