It seems you are trying to bind a BindingSource to the first DataTable with the same Type name. A direct approach would be to prepare the front of the Dictionary , which displays the names that you use to search the tables:
var tablesByName = (from set in model.DataSource from table in set.Tables select table) // get all tables of all sets .ToDictionary(table => (table.GetType() as Type).Name)
(If the tables never change, this may be a static field, which is evaluated only once.)
Then the rest of your code should be reduced to:
foreach (var source in view.DataContext) { DataTable table; var name = (source.DataSource as Type).Name; if (tablesByName.TryGetValue(name, out table)) { source.DataSource = table; } }
I missed the handling of things like tables with double names. (Which would make ToDictionary() unsuccessful, so you need to get rid of duplicates before this call.)
source share