我有两个系列. BindingSource的集合和DataSet的集合.现在,我尝试在DataSet集合的表类型中找到BindingSource集合的相应数据类型.但我的方法略显优雅.我怎么能用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;
}
}
}
最佳答案 您似乎正在尝试将BindingSource与具有相同Type类型的第一个DataTable相关联.直接的方法是预先准备一个Dictionary,将您用于查找的名称映射到表中:
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)
(如果表永远不会改变,这可能是一个仅计算一次的静态字段.)
然后你的其余代码应该减少到:
foreach (var source in view.DataContext)
{
DataTable table;
var name = (source.DataSource as Type).Name;
if (tablesByName.TryGetValue(name, out table))
{
source.DataSource = table;
}
}
我省略了处理诸如重复名称的表之类的事情. (这会使ToDictionary()失败,所以你必须在调用之前摆脱重复.)