I have a List. I would like to filter through all the rows in the list of tables to find all the rows that are in every datatable in the list.
If possible, the compare needs to be on the “ID” column that is on every row.
I have tried to solve this with Linq but got stuck. This is what I have so far:
List<DataTable> dataTables = new List<DataTable>();
// fill up the list
List<DataRow> dataRows =
dataTables.SelectMany(dt => dt.Rows.Cast<DataRow>().AsEnumerable()).
Aggregate((r1, r2) => r1.Intersect(r2));
Any suggestions?
Not a simple question. Here’s a solution (which seems too complicated to me, but it works).
To use Linq on DataTable, see this article for a start.
You could get the ids from one table like this
and from multiple tables
To intersect multiple lists, try this article. Using one of the methods there you could obtain the intersection of all of the ids.
Using Jon Skeet’s helper method
we can write
Now flatten all the rows from the DataTables and filter by the common ids:
Now group by id and take the first instance of each row: