milesma milesma - 4 years ago 148
C# Question

What is the graceful way to remove an element from C# ArrayList in a loop?

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?

Answer Source

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");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download