Collection remove

  • Thread starter Thread starter Franck Diastein
  • Start date Start date
F

Franck Diastein

Hi, I'm trying to remove items from a collection this way:

foreach(Object myO in ObjectCol){
if(myO != "xxx"){
myO.Remove();
}
}

But I'm having an error telling me that Collection was modified... I
understand this, since I remove one object from collection...

What is the best way to remove objects from my collection ?

TIA
 
Franck said:
Hi, I'm trying to remove items from a collection this way:

foreach(Object myO in ObjectCol){
if(myO != "xxx"){
myO.Remove();
}
}

But I'm having an error telling me that Collection was modified... I
understand this, since I remove one object from collection...

What is the best way to remove objects from my collection ?

TIA


What exactly class you are using? There's no ObjectCol class in .NET,at least i didn't find one.
If you are using like ArrayList, then to remove object from collection just do:

foreach(Object o in al){
if(o != "xxx"){
al.Remove(o);
}
}

where al is your ArrayList object.

Hope it helps
Andrey
 
You cannot remove while in a foreach. Use for instead. Foreach gets the
collection enumeration and relies on that enumeration for looping, but when
you delete from the collection, the foreach gets confused. So, the solution
is to use for() instead

JIM
 
MuZZy said:
What exactly class you are using? There's no ObjectCol class in
.NET,at least i didn't find one. If you are using like ArrayList,
then to remove object from collection just do:

foreach(Object o in al){
if(o != "xxx"){
al.Remove(o);
}
}

where al is your ArrayList object.

No, that's exactly the problem - that will throw an exception.

One way is to create a list of all objects you want to delete, then
remove then:

ArrayList removals = new ArrayList();
foreach (Object o in originalList)
{
if (o != "xxx")
{
removals.Add (o);
}
}

foreach (Object o in removals)
{
originalList.Remove(o);
}
 
Don't forget that if you choose to use for instead of foreach, you must
loop _backward_ through the collection:

for (int i = myCollection.Length - 1; i >= 0; i--)
{
MyItemType item = (MyItemType)myCollection.Items;
if (item.Property == "xxx")
{
myCollection.Remove(item);
}
}

If you loop forward through the collection, then removing an item will
change the indices of all succeeding items, and you will end up
skipping items....
 
thank you
No, that's exactly the problem - that will throw an exception.

One way is to create a list of all objects you want to delete, then
remove then:

ArrayList removals = new ArrayList();
foreach (Object o in originalList)
{
if (o != "xxx")
{
removals.Add (o);
}
}

foreach (Object o in removals)
{
originalList.Remove(o);
}
 
Back
Top