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

后端 未结 3 586
情书的邮戳
情书的邮戳 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:20

    Also you can iterate over the copy of your collection:

    foreach (var item in myDic.ToList())
    {
        if (item.value == 42)
        myDic.remove(item.key);
    }
    

    notice myDic.ToList() in foreach statement.

提交回复
热议问题