how to change the value of dictionary using linq based on key?
c#, dictionary, linq
Solution
`LIN(Q)` is a tool to query something not to update it. However, you can first query what you need to update. For example:
var toUpdate = customList
.Where(c => newdictionary.ContainsKey(c.SerialNo))
.Select(c => new KeyValuePair<string, string>(c.SerialNo, c.ecoID.ToString()));
foreach(var kv in toUpdate)
newdictionary[kv.Key] = kv.Value;
By the way, you get the "KeyValuePair.Value' cannot be assigned to it is read only" exception because a`KeyValuePair<TKey, TValue>` is a `struct` which cannot be modified.
Problem
I have a Dictionary which is of type, ``` Dictionary<string, string> newdictionary = new Dictionary<string, string>(); newdictionary.Add("12345", "chip1"); newdictionary.Add("23456", "chip2"); ``` Now i have a List which is of type ``` internal class CustomSerial { public string SerialNo { get; set; } public decimal ecoID { get; set; } } var customList = new List<CustomSerial>(); CustomSerial custObj1= new CustomSerial(); custObj1.ecoID =1; custObj1.SerialNo = "12345"; customList.Add(custObj1); CustomSerial custObj2 = new CustomSerial(); custObj2.ecoID = 2; custObj2.SerialNo = "23456"; customList.Add(custObj2); ``` Now i need to update the Initial dictionary by Filtering the Keys with ther SerialNumber and Replacing the values with the ecoID. When i try this, it gives ``` foreach (KeyValuePair<string, string> each in newdictionary) { each.Value = customList.Where(t => t.SerialNo == each.Key).Select(t => t.ecoID).ToString(); } ``` System.Collections.Generic.KeyValuePair.Value' cannot be assigned to -- it is read only