How to change dictionary value using linq based on key?

I have a dictionary that has a type,

  Dictionary<string, string> newdictionary = new Dictionary<string, string>();
  newdictionary.Add("12345", "chip1");
  newdictionary.Add("23456", "chip2");

Now I have a List that has 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 source dictionary by filtering the keys with SerialNumber and replacing the values ​​with ecoID.

When I try to do it, he 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 - it is read-only

+4
source share
2 answers

LIN(Q)is a tool to request that it does not update it. However, you may first ask what you need to update. For instance:

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;

, "KeyValuePair.Value" ", KeyValuePair<TKey, TValue> - struct, .

+8

: , ,

 var dictionary = new Dictionary<string, string>() { { "12345", "chip1" }, { "23456", "chip2" } };
                var customList = new List<CustomSerial>() { new CustomSerial() { ecoID = 1, SerialNo = "12345" }, new CustomSerial() { ecoID = 2, SerialNo = "23456" } };

                dictionary.Keys.ToList().ForEach(key =>
                {
                    dictionary[key] = customList.FirstOrDefault(c => c.SerialNo == key).SerialNo;
                });
+3

Source: https://habr.com/ru/post/1546973/


All Articles