would remove a key from Dictionary in foreach cause a problem? or should I better to construct a new Dictionary?

后端 未结 3 581
情书的邮戳
情书的邮戳 2021-02-12 13:49

for example:

1.

         foreach (var item in myDic)
                {
                  if (item.value == 42)
                        myDic.remove(item.         


        
3条回答
  •  终归单人心
    2021-02-12 14:07

    I would suggest making a copy of the keys and not the entire dictionary as an array, like others have suggested.

    mykeytype[] mykeys = new mykeytype[mydic.Keys.Count];
    mydic.Keys.CopyTo(mykeys, 0);
    foreach (var key in mykeys)
    {
        MyType thing;
        if (!mydic.TryGetValue(key, out thing)) continue;
    
        // remove or add to dictionary here
    }
    

提交回复
热议问题