What about this, which worked for me:
private DataTable DataTableJoiner(DataTable dt1, DataTable dt2)
{
var commonColumns = dt1.Columns.OfType<DataColumn>().Intersect(dt2.Columns.OfType<DataColumn>(), new DataColumnComparer());
var result = new DataTable();
result.Columns.AddRange(
dt1.Columns.OfType<DataColumn>()
.Union(dt2.Columns.OfType<DataColumn>(), new DataColumnComparer())
.Select(c => new DataColumn(c.Caption, c.DataType, c.Expression, c.ColumnMapping))
.ToArray());
var rowData = dt1.AsEnumerable().Join(
dt2.AsEnumerable(),
row => commonColumns.Select(col => row[col.Caption]).ToArray(),
row => commonColumns.Select(col => row[col.Caption]).ToArray(),
(row1, row2) =>
{
var row = result.NewRow();
row.ItemArray = result.Columns.OfType<DataColumn>().Select(col => row1.Table.Columns.Contains(col.Caption) ? row1[col.Caption] : row2[col.Caption]).ToArray();
return row;
},
new ObjectArrayComparer());
foreach (var row in rowData)
result.Rows.Add(row);
return result;
}
For this to work, you need to declare these 2 classes in addition:
private class DataColumnComparer : IEqualityComparer<DataColumn>
{
#region IEqualityComparer<DataColumn> Members
public bool Equals(DataColumn x, DataColumn y)
{
return x.Caption == y.Caption;
}
public int GetHashCode(DataColumn obj)
{
return obj.Caption.GetHashCode();
}
#endregion
}
private class ObjectArrayComparer : IEqualityComparer<object[]>
{
#region IEqualityComparer<object[]> Members
public bool Equals(object[] x, object[] y)
{
for (var i = 0; i < x.Length; i++)
{
if (!object.Equals(x[i], y[i]))
return false;
}
return true;
}
public int GetHashCode(object[] obj)
{
return obj.Sum(item => item.GetHashCode());
}
#endregion
}
I hope this helps!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…