1. 最初のDataTableの各行を取得し、指定されたカラムの値をキーとして、Dictionaryオブジェクトに格納します。
  2. 次に、2番目のDataTableの各行を取得し、同様に指定されたカラムの値をキーとして、Dictionaryオブジェクトに格納します。
  3. 2つのDictionaryオブジェクトを比較し、同じキーが存在し、それらの値が一致する場合は、2つのDataTableの行が一致していると見なすことができます。

以下は、このアルゴリズムを使用したC#のサンプルコードです。

 

 

using System;

using System.Collections.Generic;

using System.Data;

 

class Program

{

static void Main(string[] args)

{

// 2つのDataTableを作成する

DataTable dt1 = new DataTable();

dt1.Columns.Add("Id", typeof(int));

dt1.Columns.Add("Name", typeof(string));

dt1.Rows.Add(1, "John");

dt1.Rows.Add(2, "Mike");

dt1.Rows.Add(3, "Mary");

 

DataTable dt2 = new DataTable();

dt2.Columns.Add("Id", typeof(int));

dt2.Columns.Add("Name", typeof(string));

dt2.Rows.Add(1, "John");

dt2.Rows.Add(2, "Peter");

dt2.Rows.Add(4, "Mary");

 

// 比較するカラムを指定する

string[] columnsToCompare = { "Id", "Name" };

 

// Dictionaryオブジェクトを使用して、2つのDataTableを比較する

Dictionary<string, DataRow> dict1 = new Dictionary<string, DataRow>();

foreach (DataRow row in dt1.Rows)

{

string key = string.Empty;

foreach (string col in columnsToCompare)

{

key += row[col].ToString();

}

dict1.Add(key, row);

}

 

Dictionary<string, DataRow> dict2 = new Dictionary<string, DataRow>();

foreach (DataRow row in dt2.Rows)

{

string key = string.Empty;

foreach (string col in columnsToCompare)

{

key += row[col].ToString();

}

dict2.Add(key, row);

}

 

// 2つのDictionaryオブジェクトを比較する

foreach (string key in dict1.Keys)

{

if (dict2.ContainsKey(key))

{

DataRow row1 = dict1[key];

DataRow row2 = dict2[key];

 

bool rowsMatch = true;

foreach (string col in columnsToCompare)

{

if (row1[col].ToString() != row2[col].ToString())

{

rowsMatch = false;

break;

}

}

 

if (rowsMatch)

{

Console.WriteLine("Matching rows found:");

Console.WriteLine(string.Join(", ", columnsToCompare) + " = " + key);

Console.WriteLine("Table 1:");

Console.WriteLine(string.Join(", ", row1.ItemArray));

Console.WriteLine("Table 2:");

Console.WriteLine(string.Join(", ", row2.ItemArray));

Console.WriteLine();

}

}

}

}