【问题标题】:Delete using LINQ by joining two datatables通过连接两个数据表使用 LINQ 删除
【发布时间】:2017-04-30 12:35:39
【问题描述】:

我有两个数据表 DurationByCurrency(在数据集内)和 Fund,如下所示

我想通过执行连接删除 Duration By Currency 数据表中 FundCode 在 Fund Dt 中的值为 2 的行。

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 新手。

【问题讨论】:

    标签: c# linq datatable dataset


    【解决方案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;
    }
    

    【讨论】:

    • 在 rec1.Field("Type") 的这一行中,我收到错误“在声明之前不能使用局部变量 rec1。我需要声明 rec1 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    相关资源
    最近更新 更多