Question

I'm quite happy with Java's

ArrayList<String> list = new ArrayList<>();
Iterator<SignalEvent> it = list.iterator();
while (it.hasNext()) {
    String s = it.next();            
    if(s.equals("delete me")){
        it.remove();
    }
}

not quite happy but feels OK with C++'s

std::list<MyObject*> mylist;    
for (list<MyObject*>::iterator it = mylist.begin(); it != mylist.end();)
{
    MyObject* se = (*it);
    if(se->bDelete == true)
        it = mylist.erase(it);
    else
        it++;
}

Now comes to C#, is this the best way to do it?

Do you have an iterator way of doing it?

Do you have better suggestion considering performance and readability.

for( int i = arrayList.Count - 1; i >= 0; i -- )
{
    if( arrayList[ i ].ToString() == "del" )
    {
        arrayList.RemoveAt( i );
    }
}

Note: List.RemoveAll(Predicate match) has to introduce a new function, doesn't it?

Was it helpful?

Solution

If you don't mind creating a new list, you can use Linq, which is unquestionably graceful:

arrayList.where(x => x.toString() != "del");

Or if you still want to remove things from the list instead of using the previous solution, see if you can use a lambda expression instead:

arrayList.RemoveAll(x => x.toString() == "del");

OTHER TIPS

Try this:

ArrayList arryList2 = new ArrayList();
arryList2.Add(100);
arryList2.Add(200);
arryList2.Add(100);

Console.WriteLine(arryList2.Count);

while (arryList2.Contains(100))
    arryList2.Remove(100);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top