Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# List - Removing items while looping / iterating [duplicate]

Suppose that I have the following code snippet:

var data=new List<string>(){"One","Two","Three"}; for(int i=0 ; i<data.Count ; i++){   if(data[i]=="One"){     data.RemoveAt(i);   } } 

The following code throws exception.

My question is what is the best way to avoid this exception and to remove the element while looping?

like image 333
Ashraf Sayied-Ahmad Avatar asked Sep 07 '11 21:09

Ashraf Sayied-Ahmad


1 Answers

If you need to remove elements then you must iterate backwards so you can remove elements from the end of the list:

var data=new List<string>(){"One","Two","Three"}; for(int i=data.Count - 1; i > -1; i--) {     if(data[i]=="One")     {         data.RemoveAt(i);     } } 

However, there are more efficient ways to do this with LINQ (as indicated by the other answers).

like image 166
ChrisF Avatar answered Sep 26 '22 17:09

ChrisF