Mark Roworth
Mark Roworth

Reputation: 566

C# LINQ join to tables and the use foreach to update one of them

I have the unenviable task of working through a large legacy C# app and finding any embedded SQL that has cross-databases references in it. We're changing the security so that any connection only has access to one database at a time. Hence, I have to change such queries into two database queries to the two databases, and then perform the resulting join in memory.

I have a query that results in two DataTables dtA and dtB. I need to inner join them and update dtA. This is fairly rudimentary in SQL, but I'm having difficulties in LINQ.

So far I have:

(from a in dtA.AsEnumerable()
 join b in dtB.AsEnumerable() on a["accountno"] equals b["acc_no"]
 select a["fieldA"], b["fieldB"]).ToList().<what do I put here to update a["fieldA"] = b["fieldB"] in dtA?>

Other questions I've consulted show how to update a single set of data from itself, but I cannot find anything to do it as the result of a join. Thanks.

========

UPDATE: I am aware that the foreach is not part of LINQ, but I want to drive the update of one of the DataTables using LINQ, hence the question. I don't really want to then have to write a separate loop to do this.

Upvotes: 1

Views: 600

Answers (1)

Svyatoslav Danyliv
Svyatoslav Danyliv

Reputation: 27282

LINQ is for query, not for mutation. You can use foreach for such purpose:

var joined = 
    from a in dtA.AsEnumerable()
    join b in dtB.AsEnumerable() on a["accountno"] equals b["acc_no"]
    select (a, b);

foreach (var pair in joined)
    pair.a["fieldA"] = pair.b["fieldB"];

Upvotes: 1

Related Questions