Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using IEnumerator to removing items 2

Status
Not open for further replies.

d00ape

Programmer
Apr 2, 2003
171
SE
I want to remove some items from an ArrayList. Can I do that using a foreach(…)- loop an IEnumerator like this.

foreach(string s in arraylist)
{
if (s == “del”)
{
// Here I want to remove the item from arraylist…
}
}

Any ideas how to solve this without creating a new ArrayList and add items I want to save. Feels like that solution will bee to time consuming…

All tips are welcomed!.
 
Code:
int iIndex = 0;

while( iIndex < arrayList.Count)
{
 if( //you need to remove this item)
 {
  arrayList.RemoveAt( iIndex);
 }
 else
 {
  iIndex++;
 }
}


And it is not time consuming ;)
 
You can't remove or add items to an Arraylist inside a foreach loop (includes using IEnumerable, too). This is because doing the add/remove will alter the contents of the collection, which invalidates your IEnumerator.

You'll need to use either a traditional for loop or a while loop.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top