1

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.

Mark Roworth
  • 409
  • 2
  • 15

1 Answers1

1

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"];
Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32
  • I ended up doing something similar to that. I have seen linq queries that modify the data in the object being queried, but they only ever user one object. Example here: https://stackoverflow.com/questions/20832684/update-records-using-linq – Mark Roworth Dec 31 '22 at 13:11
  • `ForEach` is not LINQ. Architecturally LINQ is immutable and do not change anything. You also can do that with this query. – Svyatoslav Danyliv Dec 31 '22 at 13:24
  • What I'm unclear about is, in the example in the question, how do I use this type of mechanism: ```.ForEach(x => x.is_default = false);``` to update a field of dtA? I don't know how, within the ForEach, to specify the DataSets. – Mark Roworth Dec 31 '22 at 14:38