Reputation: 2921
I have some DataTables loaded into memory from various sources (SQL and MS Access), and each dataset has several columns, with only a subset of columns that are the same between each dataset. I'm working on some data synchronization code, and I want to compare these data tables, but only compare them based on the columns they have in common. If I had to I could probably do this with lots of loops, but I want to get more comfortable with LINQ and have more concise code.
Thus far I've managed to get a list of column names from each datatable, and used Intersect to get the list of column names common to both of them, like this:
private string[] Common_ColumnNames {
get {
// get column names from source & destination data
string[] src_columnNames =
(from dc in _srcDataTable.Columns.Cast<DataColumn>()
select dc.ColumnName).ToArray();
string[] dest_columnNames =
(from dc in _destDataTable.Columns.Cast<DataColumn>()
select dc.ColumnName).ToArray();
// find the column names common between the two data sets
// - these are the columns to be compared when synchronizing
return src_columnNames.Intersect( dest_columnNames ).ToArray();
}
}
Now I'm stuck... I need to select all rows from each DataTable, but only with those common columns. In my head I see this working a couple different ways:
1) select all rows from a datatable, and passing in my desired column list string[] variable to tell LINQ what columns I want
2) select all rows from a datatable, and use some lambda function (also fairly new to me) to remove the unwanted columns from each row, and outputing a new datatable with some dropped columns.
Any advice/suggestions on how to pull this off would be appreciated. Thanks!
Upvotes: 0
Views: 1697