Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update DataTable from another table with LINQ

Tags:

linq

datatable

I have 2 DataTables that look like this: 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

and I want to update DataTable 1 with the field["LOCALITATE"] using the maching key DataTable1["cheie_primara"] and DataTable2["ID_CP"]. Like this:

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

Is there a LINQ methode to update DataTable1 ? Thanks!

like image 746
XandrUu Avatar asked Feb 27 '26 20:02

XandrUu


1 Answers

This is working:

        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]));
like image 186
Ivan Golović Avatar answered Mar 02 '26 15:03

Ivan Golović