Friday, 9 December 2016

Collection was modified after the enumerator was instantiated.

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

List<string> li = new List<string>();
            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--;
            }

No comments:

Post a Comment

Note: only a member of this blog may post a comment.