Thursday, July 12, 2012

How to Compare The Two data table Columns in C sharp



Q)I have one issue , my issue is
1)i want to compare the two data table columns in C sharp
2) if columns in first datatable matches with columns in second datatable
3) i want to copy those matched column data to another datatable

please help me how to do it.
By using  your code we can compare but  if the column matches with other i want to copy entire column data to another datatable .
eg; 
datatable 1                                                  datatable 2
col1   col2   col3                                          col1     col2
1       test     mumbai                                       1       test
2       test     london                                         2      cool
3       test2   america                                        3       testing


i want to matched column data to another datatable
datatable 3
col1   col2
1        test
2
3


Answer)

DataTable datatable1=null; //Your Datatable1
DataTable datatable2=null; //Your Datatable2
DataTable dtMatchData = new DataTable("dtMatchData");
        dtMatchData = datatable1.Copy();
        foreach (DataColumn dt1col in datatable1.Columns)
        {
            if (datatable1.Columns.Contains(Convert.ToString(datatable2.Columns[dt1col.ColumnName])) == false)
            {
                dtMatchData.Columns.Remove(dt1col.ColumnName);

            }
        }


 

No comments:

Post a Comment