Combine / Union two dataset - C#

This method is example to combine two dataset into single dataset.

This method also called Union two dataset meaning that if both dataset contains same data, the combined dataset will not included.

Method Union Dataset :

   /// <summary>  
/// Creates the union of two Datasets, the values are compared for uniqueness by the given ID column name.
/// </summary>
/// <param name="ds1">First DataSet</param>
/// <param name="ds2">Second DataSet</param>
/// <param name="idColumn">ID column name</param>
public static DataSet Union(DataSet ds1, DataSet ds2, string idColumn)
{
if (ds1 == null)
{
return ds2;
}
if (ds2 == null)
{
return ds1;
}
ArrayList addTables = new ArrayList();
// Add the new rows
foreach (DataTable dt in ds2.Tables)
{
DataTable destTable = ds1.Tables[dt.TableName];
if (destTable != null)
{
// Create list of existing IDs
ArrayList existingIDs = new ArrayList();
foreach (DataRow dr in destTable.Rows)
{
int id = GetInteger(dr[idColumn], 0);
if ((id > 0) && !existingIDs.Contains(id))
{
existingIDs.Add(id);
}
}
// Add new rows
foreach (DataRow dr in dt.Rows)
{
int id = GetInteger(dr[idColumn], 0);
if ((id > 0) && !existingIDs.Contains(id))
{
// Add new row
destTable.Rows.Add(dr.ItemArray);
existingIDs.Add(id);
}
}
}
else
{
// Add full table
addTables.Add(dt);
}
}
// Add full tables
foreach (DataTable dt in addTables)
{
ds2.Tables.Remove(dt);
ds1.Tables.Add(dt);
}
return ds1;
}
/// <summary>
/// Returns the integer representation of an object or default value if not.
/// </summary>
/// <param name="value">Value to convert</param>
/// <param name="defaultValue">Default value</param>
/// <param name="culture">Culture used for conversion</param>
public static int GetInteger(object value, int defaultValue, CultureInfo culture = null)
{
if (value is int)
{
return (int)value;
}
int v;
if (Int32.TryParse(Convert.ToString(value), out v))
{
return v;
}
return defaultValue;
}


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

Popular posts from this blog

Example to disable save as certain file type in SSRS Report Viewer

How to create DataGrid or GridView in JSP - Servlet

Control Webpart Visible/Enable using macro in Kentico