【问题标题】:how to change the value of dictionary using linq based on key?如何使用基于键的 linq 更改字典的值?
【发布时间】:2014-07-03 17:40:53
【问题描述】:

我有一个类型的字典,

  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 替换值来更新初始字典。

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

  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' 不能被赋值——它是只读的

【问题讨论】:

  • serials 是什么?除此之外LIN(Q)是一个查询不更新的工具。
  • @TimSchmelter 是的新词典
  • foreach 用于从集合中检索数据你知道吗?
  • @DhavalPatel 是的,我知道,但是在获得太有用的密钥后尝试替换,忽略了这一点,有没有办法检查密钥和更新值?
  • @Sajeetharan 您最后一行代码中的ToString() 不太可能按照您的意愿行事。

标签: c# linq dictionary


【解决方案1】:

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' cannot be assigned to it is read only”异常,因为 aKeyValuePair&lt;TKey, TValue&gt; 是一个无法修改的 struct

【讨论】:

  • toUpdate 是字典吗?
  • @Sajeetharan:这是一个IEnumerable&lt;KeyValuePair&lt;string, string&gt;&gt;
  • 谢谢!测试后将其标记为答案:)
  • 不是更新它,而是添加一个新的键和值
  • @Sajeetharan:不,我首先只取字典中已有的键值:...Where(c =&gt; newdictionary.ContainsKey(c.SerialNo))
【解决方案2】:

这种形式是最简单的:虽然我不明白为什么要分配相同的值,但无论如何该方法都适用

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2016-02-20
    • 2015-11-03
    • 2021-11-01
    • 2023-01-27
    • 1970-01-01
    • 2018-06-20
    相关资源
    最近更新 更多