【问题标题】:Error for Dictionary, KeyValuePair and altering the data from a key [duplicate]字典、KeyValuePair 和更改键中的数据时出错 [重复]
【发布时间】:2016-04-26 13:18:02
【问题描述】:

我读过那些文章:

Firstsecondthird 仅适用于删除项目的情况,但我不删除它们。

我的代码:

 Dictionary<String, Object> tempList =(Dictionary<String,Object>)_ersetzeDasMitDas;

                //pfadFuerDieBildDatei
                foreach (KeyValuePair<string, Object> tempData in tempList)
                {
                    if (tempData.Key.Equals("fahrzeugGruppe"))
                    {
                        if (tempData.Value!=null)
                        {
                            if (tempData.Value.Equals("LKW"))
                            {
                                tempList["pfadFuerDieBildDatei"]=  Path.Combine(VirtualMachineKonstanten.statischeDateien, "lkw.png");
                            }
                            else if (tempData.Value.Equals("Transporter"))
                            {
                                tempList["pfadFuerDieBildDatei"]= Path.Combine(VirtualMachineKonstanten.statischeDateien, "transporter.png");
                            }
                            else
                            {
                                tempList["pfadFuerDieBildDatei"]= Path.Combine(VirtualMachineKonstanten.statischeDateien, "pkw.png");
                            }

                        }
                        else
                        {
                            //todo: logge Error "fahrzeugGruppe", der Wert ist null ?!
                            //erstmal für Testing
                            tempList["pfadFuerDieBildDatei"]= Path.Combine(VirtualMachineKonstanten.statischeDateien, "pkw.png");
                        }
                    }
            }

我明白了:

集合已修改;枚举操作可能无法执行,

在写入tempList["pfadFuerDieBildDatei"] 并再次进入循环之后。

如何解决?

【问题讨论】:

  • IEnumerable&lt;KeyValuePair&lt;String, Object&gt;&gt; ErsetzeDasMitDas签名

标签: c# dictionary key-value


【解决方案1】:

使用以下代码获取集合中的可更新元素,然后遍历新集合并进行更新:

var updatableCollection= tempList.Where(x => 
                          x.Key.Equals("fahrzeugGruppe") && x.Value != null)
                          .ToDictionary(x=> x.Key, x=> x.Value);
foreach (var item in updatableCollection)
{
   // check if (item.Value.Equals("LKW"))
   // update the required field
   // rest of condition and updates 
}

【讨论】:

  • 我得到同样的错误,当使用var updatableCollection = tempList.Where(x =&gt; x.Key.Equals("fahrzeugGruppe")) .ToDictionary(x =&gt; x.Key, x =&gt; x.Value); foreach (var item in updatableCollection) { updatableCollection["pfadFuerDieBildDatei"] = Path.Combine(VirtualMachineKonstanten.statischeDateien, "pkw.png"); }
猜你喜欢
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多