Ilist

  • Thread starter Thread starter Mike Malone
  • Start date Start date
M

Mike Malone

I have a Ilist that I need to iterate thru and remove items from the list based on part of the object.

The problem comes with the inablility to remove a item from a IList while iterating thru.

Any suggestions?
 
Mike,

Instead of iterating through using the foreach syntax, I would iterate
from Count - 1 to 0. You will have to get the item at that index, but once
you have it, you can remove it easily, and not get an exception.

The reason you iterate backwards is to prevent you from having to adjust
the indexes as you iterate through the list.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

I have a Ilist that I need to iterate thru and remove items from the list
based on part of the object.

The problem comes with the inablility to remove a item from a IList while
iterating thru.

Any suggestions?
 
Hi Mike,

You cannot remove items from the list while iterating using an enumerator: *foreach* loop or using directly IEnumerator
You do can remove items iterating thru the list using item indices (*for* or *while* loops).
As long as you have IList interface to the collection you can access the elements by index.

--
HTH
B\rgds
100 [C# MVP]
I have a Ilist that I need to iterate thru and remove items from the list based on part of the object.

The problem comes with the inablility to remove a item from a IList while iterating thru.

Any suggestions?
 
Back
Top