C# 加入动态列

C# Join with dynamic columns

我正在使用下面的查询来连接两个 table,它工作得很好。

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");

原因是,我想为多个 table 实现此连接,并且每个 table 的键列不同。

您可以使用此扩展方法。它允许您通过映射字典动态添加条件。

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 };