【问题标题】:C# Join with dynamic columnsC# 加入动态列
【发布时间】:2020-04-13 22:30:43
【问题描述】:

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

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# linq dynamic-linq


【解决方案1】:

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

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

【讨论】:

  • 这是给出 dtfile 中的所有行,而不是给出完全匹配的行。
  • 非常感谢,这太完美了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多