Reputation: 51
I am trying to update Datatable with the value of dictionary based on key getting matched with dictionary. Below is the code snippet. It is not getting updated.
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("col1");
dt.Columns.Add("value");
DataRow dr = dt.NewRow();
dr["col1"] = "key1";
dr["value"] = "No";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["col1"] = "key2";
dr["value"] = "Yes";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["col1"] = "key3";
dr["value"] = "No";
dt.Rows.Add(dr);
Dictionary<string, string> test = new Dictionary<string, string>();
test.Add("key1", "Yes");
test.Add("key2", "No");
test.Add("key3", "No");
dt.AsEnumerable().Where(r => r["col1"] == test.Select(x => x.Key)).ToList<DataRow>().ForEach(y => y["value"] = "Yes");
dt.AcceptChanges();
}
}
Upvotes: 1
Views: 6731
Reputation: 109
Is this the solution you are looking for? From my understanding of your question, I have this following method to solve the problem. When I had the similar problem this helped me to resolve the Issue.
dtNewLCM.AsEnumerable().Where(row => row.Field<string>("col1")=="key1")
.Select(b => b["value"] = "MyValue.")
.ToList();
Try this...!
Upvotes: 0
Reputation: 460138
Even if it would work that way, you are updating it with "Yes"
instead of the value from the dictionary. You're also using Enumerable.Select
instead of Dictionary.ContainsKey
which is the real problem.
So i think this will fix both:
dt.AsEnumerable()
.Where(row => test.ContainsKey(row.Field<string>("col1")))
.ToList<DataRow>()
.ForEach(row => row["value"] = test[row.Field<string>("col1")]);
Instead of creating that list to use ForEach
i'd prefer a different approach:
var newValues = from row in dt.AsEnumerable()
join kv in test on row.Field<string>("col1") equals kv.Value
select new{ DataRow = row, NewValue = kv.Value };
foreach (var x in newValues)
x.DataRow["col1"] = x.NewValue;
Upvotes: 4