使用LINQ更新基于Group的DataTable

时间:2013-12-18 09:55:11

标签: c# asp.net linq datatable

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

这是两个表:

表1:

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

表2:

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

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

DesiredTable:

   ID         Name          PaidAmount
 ------      -------        ---------
    1          AA             7000
    2          BB             6000
    3          CC             7000

通常,在要更新的SQL SERVER中,我们使用以下查询

  UPDATE
     T1
  SET
     T1.PaidAmount = T2.Amount
  FROM
     Table1 T1
     INNER JOIN
     (
       SELECT SUM(Amount) AS Amount, ID FROM Table2 GROUP BY ID
     )    T2 ON T1.ID = T2.ID

但是,如何使用LINQ实现此结果?

2 个答案:

答案 0 :(得分:1)

我试过这个,它对我来说很有效。

我已经通过考虑 LINQ to Entities

实现了此解决方案

请尝试以下代码:

 var result = from t1 in db.Table1
                     let t2 = from q in db.Table2
                              group q by q.ID into g
                              select new
                              {
                                  ID = g.Min(i => i.ID),
                                  Amount = g.Sum(i => i.Amount)
                              }
                     select new
                     {
                         t1.ID,
                         t1.Name,
                         PaidAmount = t2.Where(s => s.ID == t1.ID).FirstOrDefault().Amount,

                     };

        foreach (var res in result.ToList())
        {
            Table1 t = (from t1 in db.Table1
                        where t1.ID == res.ID
                        select t1).Single();
            t.PaidAmount = res.PaidAmount;
            db.SaveChanges();
        }

答案 1 :(得分:1)

在我看来,你必须执行两项主要操作:

  1. Table2
  2. 中汇总数据
  3. 更新Table1
  4. 中的金额

    汇总:

    var aggregatedData = db.Table2
        .GroupBy(x => x.ID)
        .Select(g => new
        {
            Id = g.Key,
            Amount = g.Sum(x => x.Amount)
        });
    

    更新:

    var joined = aggregatedData.Join(db.Table1,
            aggregatedItem => aggregatedItem.Id,
            x => x.ID,
            (aggregated, item) => new
            {
                Item = item,
                Data = aggregated
            });
    foreach(var item in joined)
    {
        item.Item.PaidAmount = item.Data.Amount;
    }
    

    保存数据:

    db.SaveChanges();