c# - C# 加入动态列
问题描述
我正在使用下面的查询来连接两个表,它工作得很好。
var joins = from filerow in dtfile.AsEnumerable()
from dbrow in dtdb.AsEnumerable().Where(x =>
filerow["PRODUCT_ID"] == x["PRODUCT_ID"]
&& filerow["COMPANY"] == x["COMPANY_NAME"]
&& filerow["BRAND"] == x["BRAND_ID"]
&& filerow["LOCATION"] == x["PLACE"]
)
select new { filerecord = filerow, db = dbrow };
我想在字典中将列名设为动态,然后使用这个字典来获取连接结果。
Dictionary<string, string> dictcolumnMapping = new Dictionary<string, string>();
dictcolumnMapping.Add("PRODUCT_ID", "PRODUCT_ID");
dictcolumnMapping.Add("COMPANY", "COMPANY_NAME");
dictcolumnMapping.Add("BRAND", "BRAND_ID");
dictcolumnMapping.Add("LOCATION", "PLACE");
原因是,我想为多个表实现此连接,并且每个表的键列都不同。
解决方案
您可以使用此扩展方法。它允许您通过映射字典动态添加条件。
public static IQueryable<DataRow> WhereByMapping(this IQueryable<DataRow> source, DataRow parentSource, Dictionary<string, string> dictcolumnMapping)
{
foreach (var map in dictcolumnMapping)
{
source = source.Where(r => parentSource[map.Key] == r[map.Value]);
}
return source;
}
那么您的查询将是:
Dictionary<string, string> dictcolumnMapping = new Dictionary<string, string>();
dictcolumnMapping.Add("PRODUCT_ID", "PRODUCT_ID");
dictcolumnMapping.Add("COMPANY", "COMPANY_NAME");
dictcolumnMapping.Add("BRAND", "BRAND_ID");
dictcolumnMapping.Add("LOCATION", "PLACE");
var joins = from filerow in dtfile.AsEnumerable().AsQueryable()
from dbrow in dtdb.AsEnumerable().AsQueryable().WhereByMapping(filerow, dictcolumnMapping)
select new { filerecord = filerow, db = dbrow };
推荐阅读
- javascript - 一旦用户在 magento 中单击关闭,就隐藏整个会话顶部的横幅
- python - 在列表理解期间无法解包返回的元组
- sql - SQL 需要从联合中删除重复项
- mongodb - Laravel jenssegers/laravel-mongodb 模型属性在更改数据库连接时未清除并运行另一个查询
- r - 在 R 中支持数据实例加权的 SVM 包
- ios - 在 Swift 中的浏览器中打开网页 url 链接
- c# - MVVM 把通用逻辑放在哪里
- sql-server - 如何在远程 SQL Server 实例上运行批量上传
- labview - 从 LabView 导出数据
- bash - 如何使关联数组查找不区分大小写?