Wednesday, August 10, 2011

Merging tables in C#.Net

Merging two data of two tables that has same schema is easy just copy data from one table to another and done but what if there is some rows that are in both tables? I used below method to merge two tables, this removes duplicates based on the primary key column.

    private static DataTable Merge(DataTable t1, DataTable t2, string primaryKey)
    {
      string key = primaryKey;
      DataTable dataTable = t1.Copy();
      dataTable.PrimaryKey = new DataColumn[1]
      {
        dataTable.Columns[key]
      };
      dataTable.BeginLoadData();
      foreach (DataRow row in t2.Rows)
      {
        if (dataTable.Rows.Find(row[key]) == null)
        {
          dataTable.ImportRow(row);
        }
      }
      dataTable.EndLoadData();
      return dataTable;
    }

  <LinearGradientBrush x:Key="{ComponentResourceKey {x:Type igDP:XamDataGrid},LabelHighlight}" LinearGradientBrush.StartPoint="0,1" LinearGradientBrush.EndPoint="0,.5" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <GradientStop GradientStop.Offset="0" GradientStop.Color="#FF457FE9" />
    <GradientStop GradientStop.Offset="0.25" GradientStop.Color="#CC3C8CBA" />
    <GradientStop GradientStop.Offset="1" GradientStop.Color="#00103475" />
  LinearGradientBrush>
  <SolidColorBrush x:Key="{ComponentResourceKey {x:Type igDP:XamDataGrid},LabelForeground}" SolidColorBrush.Color="#FFFFFFFF" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" />
  <LinearGradientBrush x:Key="{ComponentResourceKey {x:Type igDP:XamDataGrid},LabelBackground}" LinearGradientBrush.StartPoint="0,0" LinearGradientBrush.EndPoint="0,1" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <GradientStop GradientStop.Offset="0" GradientStop.Color="#FF828796" />
    <GradientStop GradientStop.Offset="0.5" GradientStop.Color="#FF424759" />
    <GradientStop GradientStop.Offset="0.5" GradientStop.Color="#FF303342" />
    <GradientStop GradientStop.Offset="1" GradientStop.Color="#FF191925" />
  LinearGradientBrush>

No comments:

Post a Comment