加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何使用基于密钥的linq更改字典的值?

发布时间:2020-12-16 00:11:22 所属栏目:百科 来源:网络整理
导读:我有一个类型的字典, Dictionarystring,string newdictionary = new Dictionarystring,string(); newdictionary.Add("12345","chip1"); newdictionary.Add("23456","chip2"); 现在我有一个类型的列表 internal class CustomSerial { public string SerialNo
我有一个类型的字典,

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

现在我有一个类型的列表

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

解决方法

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”不能被赋予它是只读的“异常,因为aKeyValuePair< TKey,TValue>是一个无法修改的结构.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读