collection modification problems

C

csharpula csharp

Hello,

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?

Thank you!
 
J

Jeroen Mostert

csharpula said:
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;
...
listA.Add(objectA);
}

Finally, you could produce the results as a new list and combine them
afterwards:

List<classA> listB = 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.
 
P

PvdG42

csharpula csharp said:
Hello,

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?

Thank you!


I hope I understand you correctly.
You want to add an item to a collection if it is not already there?
Depending on the size of your list and the frequency of the search, you
could be adding unnecessary overhead to your application.
Have you considered using a collection type that does not allow duplicates?

http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top