使用LINQ从另一个表更新DataTable

时间:2012-08-14 12:46:21

标签: linq datatable

我有2个DataTable,如下所示: DataTable 1:

cheie_primara    cheie_secundara   judet    localitate
1                11                A                
2                22                B                
3                33                C                
4                44                D                
5                55                A                
6                66                B                
7                77                C                
8                88                D                
9                99                A          

DataTable 2:

ID_CP          BAN             JUDET          LOCALITATE      ADRESA
1              11              A              aa              random
2              22              B              ss              random
3              33              C              ee              random
4              44              D              xx              random
5              55              A              rr              random
6              66              B              aa              random
7              77              C              ss              random
8              88              D              ee              random
9              99              A              xx              random

我想使用加工键DataTable1 [“cheie_primara”]和DataTable2 [“ID_CP”]用字段[“LOCALITATE”]更新DataTable 1。 像这样:

cheie_primara    cheie_secundara   judet    localitate
1                11                A        aa        
2                22                B        ss        
3                33                C        ee        
4                44                D        xx        
5                55                A        rr        
6                66                B        aa        
7                77                C        ss        
8                88                D        ee        
9                99                A        xx

是否有更新DataTable1的LINQ方法? 谢谢!

2 个答案:

答案 0 :(得分:2)

这是有效的:

        DataTable1.AsEnumerable()
            .Join(  DataTable2.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(3, o.dt2_Row.ItemArray[3]));

答案 1 :(得分:0)

如果你想使用Linq,我就是这样做的;

var a =  (from d1  in DataTable1
        join d2 in DataTable2 on d1.cheie_primara equals d2.ID_CP
        select new {d1, d2.LOCALITATE}).ToList();

a.ForEach(b => b.d1.localitate = b.LOCALITATE);