Sep 5, 2010

Import mismatched table C#

In the scenario that you have two tables of data, in which the columns from these two tables may not completely match (perhaps the source has extra unwanted information, or the destination's purpose is larger in scope) and you want to merge them, the below code can help. It gets each value that matches on both tables, then adds that row to the destination table.
txt download

/// <summary>
/// Adding all the rows of an incoming table to an existing table, where the columns may be mismatched, and dropping source values that don't match the destination is ok.
/// </summary>
///
///    09.19.10    LW: Altered the Row add line from import to Rows.Add. Method works now >.>
///    09.05.10    LW: Created. Posted online http://blog.leviwatts.com/2010/09/import-mismatched-table.html
///

/// <param name="dtSource">Table to be added to destination table</param>
/// <param name="dtDestination">Table to be receive to source table</param>
public DataTable AddTableToTable(DataTable dtSource, DataTable dtDestination)
{
    DataRow drInsert;
    foreach (DataRow drSource in dtSource.Rows)
    { //For each row in the source table, add any values that match in the destination table
        drInsert = dtDestination.NewRow();
        foreach (DataColumn dc in dtDestination.Columns)
        {
            if (dtSource.Columns.Contains(dc.ColumnName))
            {
                drInsert[dc.ColumnName] = drSource[dc.ColumnName];
            }
        }
        dtDestination.Rows.Add(drInsert);
    }

    return dtDestination;
}

No comments: