首页 > 解决方案 > 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");

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

标签: c#linqdynamic-linq

解决方案


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

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

推荐阅读