Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change the value of dictionary using linq based on key?

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

like image 958
Sajeetharan Avatar asked Dec 06 '22 01:12

Sajeetharan


2 Answers

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 aKeyValuePair<TKey, TValue> is a struct which cannot be modified.

like image 76
Tim Schmelter Avatar answered Dec 10 '22 12:12

Tim Schmelter


You'd have the simplest in this form: though I don't see why you are assigning the same value but the method applies regardless

 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;
                });
like image 25
Tsepo Mohlapo Avatar answered Dec 10 '22 12:12

Tsepo Mohlapo