We can join 2 DataTables together—each resulting row in the DataTable will contain all data from each table for the key. We must set a PrimaryKey column to use Merge.
using System;
using System.Data;
class Program
{
static void Main()
{
// Create 1 table, setting ID as PrimaryKey.
DataTable tableStyle = new DataTable(
"PictureStyle");
var idColumn = new DataColumn(
"ID", typeof(int));
tableStyle.Columns.Add(idColumn);
tableStyle.PrimaryKey = new DataColumn[] { idColumn };
tableStyle.Columns.Add(new DataColumn(
"Style", typeof(string)));
tableStyle.Rows.Add(1,
"vertical");
tableStyle.Rows.Add(2,
"square");
tableStyle.Rows.Add(3,
"panorama");
Display(tableStyle);
// Create a second table, also using ID for PrimaryKey.
DataTable tableSize = new DataTable(
"PictureSize");
var idColumnSize = new DataColumn(
"ID", typeof(int));
tableSize.Columns.Add(idColumnSize);
tableSize.PrimaryKey = new DataColumn[] { idColumnSize };
tableSize.Columns.Add(new DataColumn(
"Size", typeof(int)));
tableSize.Rows.Add(1, 50);
tableSize.Rows.Add(2, 150);
tableSize.Rows.Add(3, 250);
Display(tableSize);
// Merge the 2 tables together based on the PrimaryKey.
tableStyle.Merge(tableSize);
Display(tableStyle);
}
static void Display(DataTable table)
{
// Display merged table.
Console.WriteLine(
"::TABLE::");
foreach (DataRow row in table.Rows)
{
Console.WriteLine(
"ROW: {0}", string.Join(
",", row.ItemArray));
}
}
}
::TABLE::
ROW: 1,vertical
ROW: 2,square
ROW: 3,panorama
::TABLE::
ROW: 1,50
ROW: 2,150
ROW: 3,250
::TABLE::
ROW: 1,vertical,50
ROW: 2,square,150
ROW: 3,panorama,250