C# preventing Collection Was Modified exception

前端 未结 10 1751
梦毁少年i
梦毁少年i 2021-01-17 17:16

Does

 foreach(T value in new List(oldList) )

is dangerous (costly) when oldList contains 1 millions of object T ?

More g

10条回答
  •  时光说笑
    2021-01-17 18:17

    If you are using Foreach loop for modifying collection then you will get this error as below.

    List li = new List();
        li.Add("bhanu");
        li.Add("test");
    
        foreach (string s in li)
        {
            li.Remove(s);
        }
    

    Solution - use For Loop as below.

    for (int i = 0; i < li.Count; i++)
        {
            li.RemoveAt(i);
            i--;
        }
    

提交回复
热议问题