Inspired by samneric's answer using DataRowComparer.Default but needing something that would only compare a subset of columns within a DataTable, I made a DataTableComparer object where you can specify which columns to use in the comparison. Especially great if they have different columns/schemas.
DataRowComparer.Default works because it implements IEqualityComparer. Then I created an object where you can define which columns of the DataRow will be compared.
public class DataTableComparer : IEqualityComparer<DataRow>
{
private IEnumerable<String> g_TestColumns;
public void SetCompareColumns(IEnumerable<String> p_Columns)
{
g_TestColumns = p_Columns;
}
public bool Equals(DataRow x, DataRow y)
{
foreach (String sCol in g_TestColumns)
if (!x[sCol].Equals(y[sCol])) return false;
return true;
}
public int GetHashCode(DataRow obj)
{
StringBuilder hashBuff = new StringBuilder();
foreach (String sCol in g_TestColumns)
hashBuff.AppendLine(obj[sCol].ToString());
return hashBuff.ToString().GetHashCode();
}
}
You can use this by:
DataTableComparer comp = new DataTableComparer();
comp.SetCompareColumns(new String[] { "Name", "DoB" });
DataTable celebrities = SomeDataTableSource();
DataTable politicians = SomeDataTableSource2();
List<DataRow> celebrityPoliticians = celebrities.AsEnumerable().Intersect(politicians.AsEnumerable(), comp).ToList();