I am having a problem with ObservableCollection
. I have two ObservableCollection
. One is old the other new. I want to check if there are items in the old one that aren't there in the new one and remove them (from the old one).
public class Class1
{
private ObservableCollection<String> m_Files = new ObservableCollection<String>();
public void update()
{
ObservableCollection<String> tmp_Files = new ObservableCollection<String>();
tmp_Files.Add("Foo");
tmp_Files.Add("Bar");
this.m_Files.Add("Boing");
this.m_Files.Add("Foo");
this.m_Files.Add("Bar");
this.m_Files = RemoveObsoleteFiles(this.m_Files, tmp_Files);
}
private ObservableCollection<String> RemoveObsoleteFiles(ObservableCollection<String> files_OLD, ObservableCollection<String> files_NEW)
{
ObservableCollection<String> result = files_OLD;
foreach (String item in files_OLD)
{
if (!files_NEW.Contains(item))
{
result.Remove(item);
}
}
return result;
}
}
When the RemoveObsoleteFiles()
method is called I get an error:
System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'
Stepping through the code I noticed that when result
is changed tmp_Files
also changes.
Why is that? How do I avoid it?