Search in two collections

I have two collections. The BindingSource collection and the DataSet collection. Now I will try to find the corresponding data types of the BindingSource collection in the table types of the DataSet collection. But my approach is a bit elegant. How can I solve this problem using LINQ?

foreach (var bindindSource in view.DataContext) { var dataSource = bindindSource.DataSource; string sourceName = ((Type)dataSource).Name; foreach (var dataSet in model.DataSource) { var table = (from DataTable t in dataSet.Tables where ((Type)t.GetType()).Name.Equals(sourceName) select t).FirstOrDefault(); if (table != null) { bindindSource.DataSource = table; break; } } } 
+4
source share
1 answer

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.)

+2
source

Source: https://habr.com/ru/post/1481180/


All Articles