Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Collection was modified

When I am trying to remove element from generic list using foreach loop, I am facing following issue.

Error:

Collection was modified; enumeration operation may not execute.

My code:

  if (duplicateUsers != null && duplicateUsers.Count()> 1)
           {
                       
             foreach (var duplicateUserData in duplicateUsers)
             {
                UsersData.Remove(duplicateUserData);
             }
           }


Fix:

If you are using generic list then simply use extension method ToList() with list i.e

duplicateUsers .ToList()

Your code should be:

  if (duplicateUsers != null && duplicateUsers.Count()> 1)
           {       
             foreach (var duplicateUserData in duplicateUsers.ToList())
             {
                UsersData.Remove(duplicateUserData);
             }
           }

 

Share your answer


Share as a guest

Please subscribe me to the CodeChef4U.

By creating your new answer, you agree to the privacy policy and terms of service.