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?
 

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

Similar Threads

IList<T> and IList 6
Sorting IList<T> *in place* 9
IList .. No Sort ? 1
Generics 7
List. Add, Remove. 1
Generic abstract class 3
Interesting Iterator Trivia - Thought I would share 1
Sending Generic Object 2

Back
Top