0

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?

milesma
  • 1,561
  • 1
  • 15
  • 37
  • @VaughanHilts in his c# implementation he is iterating in reverse. `List.RemoveAll(Predicate match) has to introduce a new function`, thats right it will use LINQ. Simple loops like this are faster than using LINQ (generally). There isn't much too it, use the RemoveAll lambda for the same operation in one line of code. You decide which is more readable. – Jeremy Thompson Jul 30 '13 at 03:41
  • Technically yes, an anonymous function is introduced with a lambda, `x => x == y` being a function that takes x and returns a Boolean... so what? – Mathieu Guindon Jul 30 '13 at 03:42
  • `List.RemoveAll(s => s == "del me")` only introduce anonymous function placed right where it's used – dmay Jul 30 '13 at 03:44
  • Aside note: Why use ArrayList, when we have generic List in c# nowadays? – NineBerry Feb 05 '17 at 13:13

2 Answers2

5

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");
Ido Cohn
  • 1,685
  • 3
  • 21
  • 28
1

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);
arghtype
  • 4,376
  • 11
  • 45
  • 60