Oleg Vazhnev
Oleg Vazhnev

Reputation: 24067

Java analog of iterator to remove objects from collection

In Java I can iterate collection and remove some objects from it using Iterator.remove() method http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Iterator.html#remove()

This is very handly and natural. Like you are looking for food in the fridge and throw away food with expired date. How to do the same in c#?

I want to iterate and clean-up collection in the same loop.

There are several related question, for example How to iterate and update a list however I still can not find exact duplicate of this operation in c#

Upvotes: 3

Views: 2042

Answers (3)

Oded
Oded

Reputation: 498972

In C# you can use a for loop to iterate over a collection and in it remove items - this will work for IList<T> collections.

For safety, you should iterate backwards

for(int i = coll.Count - 1; i >= 0; i--)
{
  if(coll[i] == something)
  {
     coll.RemoveAt(i);
  }
}

If you can use LINQ, look at RemoveAll as Jon Skeet suggests. This will allow you to remove all items from the list without iterating, but simply providing a predicate.

coll.RemoveAll(i => i == something);

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500225

If you're using List<T>, there's a handy method to do this (RemoveAll), which will remove all elements which match a predicate (expressed as a delegate). For example:

List<Person> people = ...;
people.RemoveAll(person => person.Age < 18);
// Just the adults left now...

This is simpler than iterating backwards, IMO.

Of course, if you're happy to create a new list instead, you can use LINQ:

var adults = people.Where(person => person.Age >= 18).ToList();

Upvotes: 7

trailmax
trailmax

Reputation: 35106

Just use for loop counting backwards

List<string> collection = new List<String> { "Hello", "World", "One", "Two", "Three"};
collection.Dump("Original List");
for(int i = collection.Count-1; i>=0; i-- )
{
    if (collection[i] == "One"){
        collection.RemoveAt(i);
    }
}
collection.Dump("After deleting");

By the way, this is a classic example from Knuth books

Edit: this example works nicely in LINQPad - for demonstrating purposes. Dump() does not work in VS.

Upvotes: 2

Related Questions