使用LINQ更新DataTable

时间:2012-11-28 12:15:20

标签: c# asp.net visual-studio-2010 linq

我有两个具有相同标识列的数据表。我想更新一个表中的一个列值与另一个表中的其他列值。例如:

这是两个表:

表1:

       ID         Name           Amount
     ------      -------        ---------
        1          AA             0
        2          BB             0
        3          CC             0

表2:

       ID        Amount
     ------    ---------
        1        5000
        2        6000
        3        7000            

我想要的数据表应该是这样的:

DesiredTable:

       ID         Name           Amount
     ------      -------        ---------
        1          AA             5000
        2          BB             6000
        3          CC             7000

我不想使用for循环。如何使用LINQ实现此结果?

4 个答案:

答案 0 :(得分:3)

这里将Table1视为'DTTable1',将Table2视为DTTable2:

DTTable1.AsEnumerable().Join(DTTable2.AsEnumerable(), 
                     dt1_Row => dt1_Row.ItemArray[0],
                     dt2_Row => dt2_Row.ItemArray[0],
                     (dt1_Row, dt2_Row) => new { dt1_Row, dt2_Row }).ToList() 
                     .ForEach(o => o.dt1_Row.SetField(2, o.dt2_Row.ItemArray[1]));

答案 1 :(得分:0)

我只是在这里张贴以供将来参考....

如果您想使用dtblToUpdateFrom中的值更新dtblToUpdate,但您需要加入多个列,那么这似乎有效:

dtblToUpdate.Rows.Cast<DataRow>().Join(dtblToUpdateFrom.Rows.Cast<DataRow>(),
            r1 => new { p1 = r1["ColToJoinOn1"], p2 = r1["ColToJoinOn2"] },
            r2 => new { p1 = r2["ColToJoinOn1"], p2 = r2["ColToJoinOn2"] },
            (r1, r2) => new { r1, r2 }).ToList()
            .ForEach(o => o.r1.SetField("ColToUpdate", o.r2["ColToUpdateFrom"]));

如果有任何问题请告诉我。

更新

以下是一些测试代码,表明它有效:

        DataTable dtblToUpdate = new DataTable();
        dtblToUpdate.Columns.AddRange(new DataColumn[]{new DataColumn("ColToJoinOn1"), new DataColumn("ColToJoinOn2"), new DataColumn("ColToUpdate")});
        dtblToUpdate.Rows.Add("1", "1", "nothing");
        dtblToUpdate.Rows.Add("2", "1", "nothing");
        dtblToUpdate.Rows.Add("3", "1", "nothing");

        DataTable dtblToUpdateFrom = new DataTable();
        dtblToUpdateFrom.Columns.AddRange(new DataColumn[]{new DataColumn("ColToJoinOn1"), new DataColumn("ColToJoinOn2"), new DataColumn("ColToUpdateFrom")});
        dtblToUpdateFrom.Rows.Add("1", "1", "something");
        dtblToUpdateFrom.Rows.Add("2", "1", "something");
        dtblToUpdateFrom.Rows.Add("3", "2", "something"); //Won't be updated since ColToJoinOn2 does not match in dtlbToUpdate

        Console.WriteLine("dtblToUpdate before update:");
        foreach(DataRow drow in dtblToUpdate.Rows)
        {
            Console.WriteLine(drow["ColToJoinOn1"].ToString() + "." + drow["ColToJoinOn2"].ToString() + " - " + drow["ColToUpdate"].ToString());
        }

        dtblToUpdate.Rows.Cast<DataRow>().Join(dtblToUpdateFrom.Rows.Cast<DataRow>(),
        r1 => new { p1 = r1["ColToJoinOn1"], p2 = r1["ColToJoinOn2"] },
        r2 => new { p1 = r2["ColToJoinOn1"], p2 = r2["ColToJoinOn2"] },
        (r1, r2) => new { r1, r2 }).ToList()
        .ForEach(o => o.r1.SetField("ColToUpdate", o.r2["ColToUpdateFrom"]));

        Console.WriteLine("dtblToUpdate after update:");
        foreach(DataRow drow in dtblToUpdate.Rows)
        {
            Console.WriteLine(drow["ColToJoinOn1"].ToString() + "." + drow["ColToJoinOn2"].ToString() + " - " + drow["ColToUpdate"].ToString());
        }

输出:

dtblToUpdate before update:
1.1 - nothing
2.1 - nothing
3.1 - nothing
dtblToUpdate after update:
1.1 - something
2.1 - something
3.1 - nothing

另外,请参阅此帖子,了解当一个表缺少Amount列时的另一个选项。您可以在一列上连接表,并获取一个新的DataTable,其中包含两个表之间的所有唯一列:How to Left Outer Join two DataTables in c#?

答案 2 :(得分:0)

我不喜欢我在网上看到的任何例子,所以这是我的例子

        DataTable dt = new DataTable();
        dt.Columns.Add("Year");
        dt.Columns.Add("Month");
        dt.Columns.Add("Views");
        for (int year = 2011; year < 2015; year++)
        {
            for (int month = 1; month < 13; month++)
            {
                DataRow newRow = dt.NewRow();
                newRow[0] = year;
                newRow[1] = month;
                newRow[2] = 0;
                dt.Rows.Add(newRow);
            }
        }

        dataGridView1.DataSource = dt;

        //if using Lambda 
        //var test = dt.AsEnumerable().Where(x => x.Field<string>("Year") == "2013" && x.Field<string>("Month") == "2").ToList();

        var test = (from x in dt.AsEnumerable()
                    where x.Field<string>("Year") == "2013"
                    where x.Field<string>("Month") == "2"
                    select x).ToList();

         var records = from p in dt.AsEnumerable()
                            where p.Field<string>("Year") == "2013" && p.Field<string>("Month") == "2"
                            select new
                            {
                                Views = p.Field<string>("Views")//,
                                //Month = p.Field<string>("Month")
                            };
                        foreach (var record in records)
                        {
                            //Console.WriteLine(string.Format("{0}. {1}  ({2})", record.Views, record.Month, record.Views));
                            thisCount = Convert.ToInt32(record.Views);
                            thisCount++;
                        }
        test[0][2] = thisCount.ToString();

        dt.AcceptChanges();

        //if writing to sql use  dt.SubmitChanges() instead

答案 3 :(得分:-1)

您可以使用join语句:

from item1 in table1
join item2 in table2 on item1.ID equals item2.ID
select new YourType { ID = item1.ID, Name = item1.Name, Amount = item2.Amount }