2016-12-15 56 views
0

我有两个数据表DurationByCurrency基金它看起来像下面 enter image description here删除使用LINQ通过连接两个数据表

我想删除时间行通过货币数据表,其(数据集内)和FundCode的值为中的2基金 Dt通过执行加入。

var result = from table1 in raptorDS.Tables[RaptorTable.DurationByCurrency].AsEnumerable() 
           join table2 in fundDT.AsEnumerable() 
           on table1.Field<string>("FundCode") equals table2.Field<string>("FundCode") into ps 
           from row in ps.DefaultIfEmpty() 
           { 
            //delete query 
           } 

请帮助我,因为我是新来的LINQ。

回答

1
var result = from row1 in raptorDS.Tables[RaptorTable.DurationByCurrency].AsEnumerable() 
           join row2 in fundDT.AsEnumerable() 
           on row1.Field<string>("FundCode") equals row2.Field<string>("FundCode") 
           where row1.Field<string>("value") 
            equals "2" select row1; 

result.ToList().ForEach(row => row.Delete()); 

为linqpad样品测试代码:

void Main() 
{ 
    //sample data for test 
    DataSet ds = new DataSet(); 
    ds.Tables.Add(GetTable1()); 
    ds.Tables.Add(GetTable2()); 

    var result = (from rec1 in ds.Tables[0].AsEnumerable() 
    join rec2 in ds.Tables[1].AsEnumerable() 
    on rec1.Field<string>("FC") equals rec2.Field<string>("FC") 
    where rec2.Field<int>("Value") == 2 select rec1); 

    result.ToList().ForEach(row => row.Delete()); 
    //now you have only "ABCD" and "AZY" in table 1 
    //ds.Tables[0].Dump(); linqpad display result 
} 

DataTable GetTable1() 
{ 
    DataTable table = new DataTable(); 
    table.Columns.Add("FC", typeof(string)); 
    table.Rows.Add("ABCD"); 
    table.Rows.Add("XYZ"); 
    table.Rows.Add("AZY"); 
    return table; 
} 

DataTable GetTable2() 
{ 
    DataTable table = new DataTable(); 
    table.Columns.Add("FC", typeof(string)); 
     table.Columns.Add("Value", typeof(int)); 
    table.Rows.Add("ABCD", 1); 
    table.Rows.Add("XYZ", 2); 
    table.Rows.Add("AZY",3); 
    return table; 
} 
在这一行
+0

其中rec1.Field (“类型”),我得到的错误声明之前,“不能使用局部变量REC1做我。需要申报rec1? –

+0

@ManivannanKG检查我的更新代码 – Damith