Reputation: 3594
I'm getting this error
System.InvalidOperationException: 'List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.'
Because in my code, the Selected Items change during iteration
The code is simple
var items = testListBox.SelectedItems;
foreach (var item in items)
{
}
I want to freeze the items list in a variable, so that if it changes, the foreach
loop doesn't change and create this error
The problem is the line var items = testListBox.SelectedItems;
doesn't seem to work, because for some reason it still gives me this error
How can I clone the SelectedItems list to another variable so it doesn't crash on the foreach loop if the SelectedItems list changes
Thanks,
Upvotes: 1
Views: 529
Reputation: 150108
Your code creates an alias called items
that refers to SelectedItems
. It doesn't make a copy.
It seems like an easy fix would be:
var items = testListBox.SelectedItems.ToList();
Alas, the WinForms collections are so old they don't support IEnumerable<T>
and so aren't fully supported by Linq. Instead, first cast the selected items to object
(or any other appropriate type):
var items = testListBox.SelectedItems.OfType<object>().ToList();
It's not clear what you might be doing in the foreach
loop to cause the error you report. You cannot modify the thing you are enumerating. However, you can enumerate over your copy and modify the original (or vice-versa).
Upvotes: 2
Reputation: 329
You can do various things to fix this, ex:
foreach (var item in items.ToArray())
{
items.Add(new Item...);
}
Or
for (int i = 0; i < items.Count; i++)
{
items.Add(new Item...);
}
See What is the best way to modify a list in a 'foreach' loop? for an in depth answer as to why this happens and what the best ways to modify items in a foreach loop are.
Upvotes: 1