Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask question.(5)

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

ITtutoria

ITtutoria Logo ITtutoria Logo

ITtutoria Navigation

  • Python
  • Java
  • Reactjs
  • JavaScript
  • R
  • PySpark
  • MYSQL
  • Pandas
  • QA
  • C++
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Python
  • Science
  • Java
  • JavaScript
  • Reactjs
  • Nodejs
  • Tools
  • QA
Home/ Questions/Amazing Solutions For the collection was modified enumeration operation may not execute Error
Next
Answered
Jade Cohen
  • 29
Jade Cohen
Asked: May 12, 20222022-05-12T11:28:26+00:00 2022-05-12T11:28:26+00:00In: csharp

Amazing Solutions For the collection was modified enumeration operation may not execute Error

  • 29

. Advertisement .

..3..

. Advertisement .

..4..

How to check – collection was modified enumeration operation may not execute? I have the sample detail:

using System;
using System.Collections.Generic;
namespace DemoApplication {
   public class Program {
      static void Main(string[] args) {
         try {
            var studentsList = new List<Student> {
               new Student {
                  Id = 1,
                  Name = "John"
               },
               new Student {
                  Id = 0,
                  Name = "Jack"
               },
               new Student {
                  Id = 2,
                  Name = "Jack"
               }
            };
            foreach (var student in studentsList) {
               if (student.Id <= 0) {
                  studentsList.Remove(student);
               }
               else {
                  Console.WriteLine($"Id: {student.Id}, Name: {student.Name}");
               }
            }
         }
         catch(Exception ex) {
            Console.WriteLine($"Exception: {ex.Message}");
            Console.ReadLine();
         }
      }
   }
   public class Student {
      public int Id { get; set; }
      public string Name { get; set; }
   }
}

While I run it, I found the warning message:

Id: 1, Name: John 
Exception: Collection was modified; enumeration operation may not execute.

That is my question in my midterm exam, and it is urgent. I searched for the key on some websites, but I didn’t get it. I may miss any line or other changes. I appreciate your assistance!

collection was modified
  • 2 2 Answers
  • 51 Views
  • 0 Followers
  • 0
Answer
Share
  • Facebook
  • Report

2 Answers

  • Voted
  • Oldest
  • Recent
  • Random
  1. Best Answer
    lyytutoria Expert
    2022-05-31T02:18:49+00:00Added an answer on May 31, 2022 at 2:18 am

    The cause: The foreach loop is runned on the studentsList. The Id of the student is 0, the item will be removed from the studentsList. Due to this change the studentsList gets modified (resized) and an exception occurs during the runtime.

    Solution: Perform a ToList() operation on the studentsList before the start of each iteration.

    foreach (var student in studentsList.ToList())
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Threading.Tasks;
    namespace DemoApplication {
       public class Program {
          static void Main(string[] args) {
             var studentsList = new List<Student> {
                new Student {
                   Id = 1,
                   Name = "John"
                },
                new Student {
                   Id = 0,
                   Name = "Jack"
                },
                new Student {
                   Id = 2,
                   Name = "Jack"
                }
    
             };
             foreach (var student in studentsList.ToList()) {
                if (student.Id <= 0) {
                   studentsList.Remove(student);
                }
                else {
                   Console.WriteLine($"Id: {student.Id}, Name: {student.Name}");
                }
             }
             Console.ReadLine();
          }
       }
       public class Student {
          public int Id { get; set; }
          public string Name { get; set; }
       }
    }

    Output

    Id: 1, Name: John 
    Id: 2, Name: Jack
    • 19
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
  2. Lucas Maury
    2022-05-25T19:44:06+00:00Added an answer on May 25, 2022 at 7:44 pm

    Unsubscribe a subscriber to change the contents of the Collection of Subscribers during Enumeration.

    This can be fixed in a number of ways, including changing the for loop to use an explicitly .ToList()

    public void NotifySubscribers(DataRecord sr) 
    {
     foreach(Subscriber s in subscribers.Values.ToList())
     {
     ^^^^^^^^^ 
     ...
    • 11
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question
  • How to Split String by space in C++
  • How To Convert A Pandas DataFrame Column To A List
  • How to Replace Multiple Characters in A String in Python?
  • How To Remove Special Characters From String Python

Explore

  • Home
  • Tutorial

Footer

ITtutoria

ITtutoria

This website is user friendly and will facilitate transferring knowledge. It would be useful for a self-initiated learning process.

@ ITTutoria Co Ltd.

Tutorial

  • Home
  • Python
  • Science
  • Java
  • JavaScript
  • Reactjs
  • Nodejs
  • Tools
  • QA

Legal Stuff

  • About Us
  • Terms of Use
  • Privacy Policy
  • Contact Us

DMCA.com Protection Status

Help

  • Knowledge Base
  • Support

Follow

© 2022 Ittutoria. All Rights Reserved.

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.