问题
I am comparing two datatables using the answer in this link Compare two Datatables but when I use the DataRelation function I am getting an error that both columns length should match. but I want to only compare specific columns.
Currently I have it this way:
// Using a Dataset to make use of a DataRelation Object
using (DataSet ds = new DataSet())
{
//Add Tables
ds.Tables.AddRange(new DataTable[] { dt.Copy(), dataTable.Copy() });
//Get First Columns for DataRelation
DataColumn[] firstcolumns = new DataColumn[7];
firstcolumns[0] = ds.Tables[0].Columns[0];
firstcolumns[1] = ds.Tables[0].Columns[1];
firstcolumns[2] = ds.Tables[0].Columns[2];
firstcolumns[3] = ds.Tables[0].Columns[3];
firstcolumns[4] = ds.Tables[0].Columns[4];
firstcolumns[5] = ds.Tables[0].Columns[5];
firstcolumns[6] = ds.Tables[0].Columns[6];
//Get Second Columns for DataRelation
DataColumn[] secondcolumns = new DataColumn[8];
secondcolumns[0] = ds.Tables[1].Columns[0];
secondcolumns[1] = ds.Tables[1].Columns[1];
secondcolumns[2] = ds.Tables[1].Columns[2];
secondcolumns[3] = ds.Tables[1].Columns[3];
secondcolumns[4] = ds.Tables[1].Columns[4];
secondcolumns[5] = ds.Tables[1].Columns[5];
secondcolumns[6] = ds.Tables[1].Columns[6];
secondcolumns[7] = ds.Tables[1].Columns[7];
//Create DataRelation
DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);
ds.Relations.Add(r);
//Create Columns for return table
for(int i = 0; i < dt.Columns.Count ; i++ )
{
ResultDataTable.Columns.Add(dt.Columns[i].ColumnName, dt.Columns[i].DataType);
}
//If first Row not in second, add to return table
ResultDataTable.BeginLoadData();
foreach( DataRow parentrow in ds.Tables[0].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r);
if (childrows != null || childrows.Length != 0)
{
ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
}
}
ResultDataTable.EndLoadData();
ResultDataTable.AsDataView();
//Export to Excel
ResultDataTable.WriteXml("data.xls");
}
What I want to do is if all the columns in firstcolumns match columns 1, 2, 3, 4, 5, 6, 7 in second columns load the all the second columns (including 0) into the resultdatatable
Please can you advice how I can do this?
回答1:
I solved this using LINQ. Got a bit of help on Stackoverflow. Following is the link to my question: Compare datatables using LINQ
来源:https://stackoverflow.com/questions/56345111/datarelation-how-to-compare-specific-columns