C Method for Traversing Collections and Removing Elements

  • 2021-10-24 23:36:12
  • OfStack

This article illustrates the method of C # traversing collections and removing elements. Share it for your reference, as follows:

If foreach is used, it will cause abnormal problems after the traversed collection changes.

At this time, for loop can effectively solve this problem.


for(int i=0;i<List.Count;i++)
{
 if( The condition is true )
 {
 List.Remove(List[i]);
 i--;
 }
}

Or, use another List collection to store the objects to be deleted.


List<T> newlists=new List<T>();
foreach(T t in List)
{
 lists.add(t);
}
foreach(T t in newlists)
{
 List.Remove(t);
}

More readers interested in C # can check the topic of this site: "C # Traversal Algorithm and Skills Summary", "C # Programming Thread Use Skills Summary", "C # Operating Excel Skills Summary", "C # Common Control Usage Tutorial", "WinForm Control Usage Summary", "C # Data Structure and Algorithm Tutorial", "C # Array Operation Skills Summary" and "C # Object-Oriented Programming Introduction Tutorial"

I hope this article is helpful to everyone's C # programming.


Related articles: