在连接两个数据表期间无效的匿名类型成员声明符

时间:2013-09-30 11:38:13

标签: c# asp.net linq datatable anonymous

我尝试进行以下加入:

var collection = from t1 in dt1.AsEnumerable()
                 join t2 in dt2.AsEnumerable()
                 on  new { 
                     t1.["main_code"], 
                     t1["year"]} 
                     equals new { 
                         t2["dep_code"], 
                         t2["dep_year"] }
                         select new { 
                             emp_name = t1["name"], 
                             bonus_desc = t1["bonus_desc"],
                             dep_name = t2["dep_name"] };

但是我面临以下构建错误!!

  

无效的匿名类型成员声明符

3 个答案:

答案 0 :(得分:4)

匿名类型join的名称属性:

var collection = from t1 in dt1.AsEnumerable()
                 join t2 in dt2.AsEnumerable()
                 on  new { PropertyA= t1["main_code"], PropertyB=t1["year"]} equals new { PropertyA=t2["dep_code"], PropertyB=t2["dep_year"] }
                 select new { emp_name = t1["name"], bonus_desc = t1["bonus_desc"],dep_name = t2["dep_name"] };

答案 1 :(得分:4)

您需要明确命名属性,例如:

var collection = 
    from t1 in dt1.AsEnumerable()
    join t2 in dt2.AsEnumerable()
    on new { code = t1["main_code"], year = t1["year"] } equals 
       new { code = t2["dep_code"], year = t2["dep_year"] }
    select new { emp_name = t1["name"], bonus_desc = t1["bonus_desc"] /* ... */};

答案 2 :(得分:3)

使用:

var collection = from t1 in dt1.AsEnumerable()
                 join t2 in dt2.AsEnumerable()
                 on  new { field1 = t1.["main_code"], field2 = t1["year"]} equals new { field1 = t2["dep_code"], field2 = t2["dep_year"] }
                 select new { emp_name = t1["name"], bonus_desc = t1["bonus_desc"],dep_name = t2["dep_name"] };