如何使用基于键的linq更改字典的值? [英] how to change the value of dictionary using linq based on key?

查看:112
本文介绍了如何使用基于键的linq更改字典的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本类型的字典

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

现在,我需要通过使用序列号过滤键并用ecoID替换值来更新初始字典.

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'不能分配给它-只读

System.Collections.Generic.KeyValuePair.Value' cannot be assigned to -- it is read only

推荐答案

LIN(Q)是用于查询某些内容而不对其进行更新的工具. 但是,您可以首先查询您需要更新的内容.例如:

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;

顺便说一句,您会收到无法将KeyValuePair.Value分配给它的值是只读的"异常,因为a KeyValuePair<TKey, TValue>是一个不能修改的struct.

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.

这篇关于如何使用基于键的linq更改字典的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆