动态Linq查询数据表

时间:2017-10-09 10:53:43

标签: sql entity-framework linq

我有两个数据表说cSVData和sqlData我想比较这两个数据表记录是否相同所以我使用这个查询

        var matched = from table1 in cSVData.AsEnumerable()
                      join table2 in sqlData.AsEnumerable() on 
                      table1.Field<string>("GlobalRank") equals table2.Field<string>("GlobalRank")
                      where
                      table1.Field<string>("GlobalRank") == table2.Field<string>("GlobalRank") 
                      || table1.Field<string>("TldRank") == table2.Field<string>("TldRank") 
                      || table1.Field<string>("Domain") == table2.Field<string>("Domain")
                      ||  table1.Field<string>("TLD") == table2.Field<string>("TLD")
                      || table1.Field<string>("RefSubNets") == table2.Field<string>("RefSubNets")
                      || table1.Field<string>("RefIPs") == table2.Field<string>("RefIPs")
                      || table1.Field<string>("IDN_Domain") == table2.Field<string>("IDN_Domain")
                      || table1.Field<string>("IDN_TLD") == table2.Field<string>("IDN_TLD")
                      || table1.Field<string>("PrevGlobalRank") == table2.Field<string>("PrevGlobalRank")
                      || table1.Field<string>("PrevTldRank") == table2.Field<string>("PrevTldRank")
                      || table1.Field<string>("PrevRefSubNets") == table2.Field<string>("PrevRefSubNets")
                      select table1;

但是这个表的列名必须是动态意味着在where子句中它应该采用所有列名

1 个答案:

答案 0 :(得分:1)

假设您的cSVDatasqlData来源为DataTables,您应该能够使用lambda语法逐步完成列:

var match = from table1 in cSVData.AsEnumerable()
            join table2 in sqlData.AsEnumerable() on
            table1.Field<string>("GlobalRank") equals table2.Field<string>("GlobalRank")
            select new { table1, table2 };
foreach (var colname in cSVData.Columns.Cast<DataColumn>().Select(c => c.ColumnName))
    if (colname != "GlobalRank")
        match = match.Where(both => both.table1.Field<string>(colname) == both.table2.Field<string>(colname));

match = match.Select(both => both.table1);