如何使用基于键的linq更改字典的值?

时间:2014-07-03 09:11:42

标签: c# linq dictionary

我有一个类型为

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

现在我有一个类型为

的List
   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);

现在我需要通过使用SerialNumber过滤密钥并使用ecoID替换值来更新初始字典。

当我尝试这个时,它会给出

  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' - 它是只读的

2 个答案:

答案 0 :(得分:9)

LIN(Q)是一种查询不更新内容的工具。 但是,您可以先查询需要更新的内容。例如:

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,无法修改。

答案 1 :(得分:3)

你有这种形式最简单的方法:虽然我不明白为什么你要分配相同的价值,但无论

是什么方法都适用
 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;
                });
相关问题