0

The code below fails, and I guess it's cause the Remove()-method is ruining the loop order. But how do I fix it?

List<string> test = new List<string>();
List<string> test2 = new List<string>();
test.Add("test");
test.Add("test");
test.Add("test");
test.Add("test");
foreach(string t in test)
{
    test2.Add(t);
    test.Remove(t);
}

2 Answers 2

5

You are right about the problem, the solution is to iterate over a copy instead of the actual list

foreach(string t in test.ToList())
{
     test2.Add(t);
     test.Remove(t);
}

BTW, you can do what you want without using any loop:

test2.AddRange(test);
test.Clear();
Sign up to request clarification or add additional context in comments.

Comments

0

It fails because foreach iteration variables or read-only.

One way to work around the error is to change the foreach loop to a for loop, starting the loop from the last element so as to not mess up the order if you remove an element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.