csharpula csharp wrote:
I am trying to iterate through list:
foreach (classA objectA in listA)
{
//if there is no objectA with specific name in list A then:
listA.add(objectA)
}
But it seems like this is an exception to modify the collection that I
am iterationg through. How to solve this?
One option is to, well, not modify the collection you're iterating through,
but use a copy instead:
foreach (classA objectA in new List<classA>(listA)) { // or listA.ToArray()
...
listA.Add(objectA);
}
Another option is to iterate in a way that will not fail when new elements
are added:
int count = listA.Count;
for (int i = 0; i != count; ++i) {
classA objectA = listA[i];
...
listA.Add(objectA);
}
Finally, you could produce the results as a new list and combine them
afterwards:
List<classAlistB = new List<classA>();
foreach (classA objectA in listA) {
...
listB.Add(objectA);
}
listA.AddRange(listB);
If all you're actually doing is appending elements, option #2 will generally
be the most efficient since no additional memory is allocated beyond what
you need for the extra elements.
--
J.