LINQ to DataTable Update Question

Poolcorp used Ask the Experts™
Howdy, I am using C# and need a quick run down on how to do something with LINQ, at least I assume it can be done with LINQ. Basically here is what I need to do

I have a data table I have pulled from a server that has some GUIDs in it, I need to match those GUIDs to their respective GUIDS on my side and get the corresponding ID values, then in turn update my DataTable with said ID values.

So in other words I have a datatable that looks something like

Name     PhoneNumber      GUID        ID
Jim         123-456-7890      SDFSG  
Mark       234-424-1453     1GDE3  

and after I run said update process on it i will have

Name     PhoneNumber      GUID        ID
Jim         123-456-7890      SDFSG     234
Mark       234-424-1453     1GDE3     266

Help would be greatly appreciated. Thanks
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Linq is a query only language. Are you using Linq-to-SQL or the Entity framework perchance?

If not, you'll need to do your query to match the GUIDs, then just iterate your matches and update the database.

You're query will look something like this, or you could use a join, up to you...

List<WebUsers> managedUsers = new List<WebUsers>();

// pretend we have some users in memory here, or from a local
// database, whatever

var users = 
	from user1 in WebUsers
	from user2 in managedUsers
	where user1.GUID == user2.GUID
	select new WebUser
		GUID = user1.GUID,
		PhoneNumber = user1.PhoneNumber,
		ID = user2.Id // managed (in-memory) ID
foreach (var user in users)
	// update the database however you're currently doing so

Open in new window

Distinguished Expert 2017
Hi Poolcorp;

This should do what you want.

// The MyDataTable is what you call "on my side"
// DBDataTable id the data that was pulled down from the database

var results = from mt in MyDataTable.AsEnumerable()
              from dbt in DBDataTable.AsEnumerable()
              where mt.Field<Guid>("GUID") == dbt.Field<Guid>("GUID")
              select new { mt, dbt };

// Iterate through the rows and update the MyDataTable with the ID values
foreach (var row in results)
{"ID", row.dbt.Field<Int32>("ID"));

Open in new window


Thanks! Worked like a charm
Fernando SotoRetired
Distinguished Expert 2017

Not a problem, glad I was able to help.  ;=)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial