C # The way to traverse list and delete an element, what method do you use to implement the first reaction? Foreach? For
If it's foreach, then congratulations, you're wrong. If you're thinking of using for, then you're just a step away from success.
the correct approach is to use a for reverse traversal , which is deleted according to the condition . Below we use code to demonstrate foreach,for Delete list data:
classProgram { Public classStudents { Public stringName {Get;Set; } Public intAge {Get;Set; } PublicStudents (stringNameintAge ) { This. Name =name; This. Age =Age ; } } Static voidMain (string[] args) {List<Students> stulist =NewList<students>(); Stulist.add (NewStudents ("Tom", -)); Stulist.add (NewStudents ("Tang", -)); Stulist.add (NewStudents ("Tang", A)); Stulist.add (NewStudents ("Trista", -)); Stulist.add (NewStudents ("Lili", -)); //Print nameConsole.Write ("before deletion:"); foreach(varStuinchstulist) Console.Write (Stu. Name+" "); Console.readkey (); } }
Print Result: Tom Tang Tang Trista Lili
1. First use the foreach traversal to delete the student named Tang, with the following code:
foreach (var in stulist) { if"Tang") Stulist.remove (stu);}
will report the following error:
Because deleting an element in foreach causes each deletion to change the size of the collection and the index value of the element, an exception occurs when an element is removed from the foreach.
2. With a for positive sequence traversal Delete, the code is as follows:
//Print nameConsole.Write ("before deletion:"); foreach(varStuinchstulist) Console.Write (Stu. Name+" "); //Delete a student named Tang for(intI=0;i< stulist.count;i++) { if(Stulist[i]. Name = ="Tang") Stulist.remove (Stulist[i]); } //Print nameConsole.Write ("\ n after deletion:"); foreach(varStuinchstulist) Console.Write (Stu. Name+" ");
Results:
Only one student named Tong was deleted. Why does this happen?
This is because when the i=1 is satisfied, the first tong is removed, and the second Tong is moved to the position of the first Tong, that is, cursor 1 corresponds to the second tong.
Then traverse the i=2 and skip the second tong.
3. Use for reverse traversal Delete, the code is as follows:
for (int i = stulist.count-1; i>=0; i--) { if"Tang") stulist.remove (Stulist[i]); }
Results:
At this time, all students named Tong were removed.
C # a way to traverse a list and delete an element