XandrUu
XandrUu

Reputation: 1179

Update DataTable from another table with LINQ

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!

Upvotes: 3

Views: 9169

Answers (2)

Ivan Golović
Ivan Golović

Reputation: 8832

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]));

Upvotes: 3

saj
saj

Reputation: 4796

If you want to use Linq, here's how I'd go about it;

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);

Upvotes: 0

Related Questions