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>是一个无法修改的结构. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ruby – 为什么我们不能在救援中访问局部变量?
- objective-c – bridged cast:__bridge_transfer vs __bri
- [Swift]LeetCode63. 不同路径 II | Unique Paths II
- 关于Flashback table tablename to before drop的应用—恢复
- ruby-on-rails – 如何在该应用程序中显示rails应用程序的g
- Oracle 11gR2 – 查看功能列评估
- JSONP跨域
- React+webpack开发环境的搭建
- ios – 完全删除XCode Target
- ruby-on-rails – REST架构究竟是什么,它在Rails中如何实现