Search code examples
c#datatablecompare

Compare 2 tables columns names, add it if doesn't exist


I have a question about comparing 2 tables. If in tables 1 doesn't contain column's name from tables 2, add the column with values. So i did it with my code, but don't know why it gives me error that the column already belongs to tables1. What did i do wrong here? Is there any better way to do it?

Example, table1:

Name   LastName
a       aa
b       bb

table2:

Name    Product
s       dd
a       ss

result:

Name   LastName    Product
a       aa         dd
b       bb         ss      

My code:

 for (int i = 0; i < excelTb2.Columns.Count; i++)
                {
                    for (int j = 0; j < Temp.Columns.Count; j++ )
                    {
                        if (Temp.Columns[j].ColumnName.ToString() != excelTb2.Columns[i].ColumnName.ToString())
                        {
                            excelTb2.Columns.Add(Temp.Columns[j].ColumnName.ToString());

                            for (int ok = 0; ok < 2; ok++)
                            {
                                excelTb2.Rows[ok][Temp.Columns[j].ColumnName] = Temp.Rows[ok][j];
                            }

                        }
                    }
                }

Solution

  • Columns is a collection. You could check if the column name is already present using Contains

    for (int j = 0; j < Temp.Columns.Count; j++ )
    {
        if(!excelTb2.Columns.Contains(Temp.Columns[j].ColumnName))
        {
            excelTb2.Columns.Add(Temp.Columns[j].ColumnName.ToString());
            ...
        }
    }
    

    This will remove the need of the nested loop that is the main cause of the error you get