C # traversal The list and delete one or several elements of the method, your first reaction using what method to implement it? 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:
Class program {public class Students {public string Name {get; set;} public int Age {get; set;} Public Students (string name, int.) {this . name = name; This. Age = Age; } } static void Main (string[] args) { list<students> stulist = new list<students> (); Stulist.add (New Students ("Tom")); Stulist.add (New Students ("Tang")); Stulist.add (New Students ("Tang",)); Stulist.add (New Students ("Trista",)); Stulist.add (New Students ("Lili"); Print name console.write ("before delete:"); foreach (Var stu in stulist) 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 stu in stulist) { if (stu. Name = = "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 name console.write ("before delete:"); foreach (Var stu in stulist) Console.Write (Stu. Name + ""); Delete the student for (int i=0;i< stulist.count;i++) { if (stulist[i) named Tang. Name = = "Tang") Stulist.remove (Stulist[i]); } Print name console.write ("\ n deleted:"); foreach (Var stu in stulist) Console.Write (Stu. Name + "");
Results:
Only one student named Tang was deleted. Why does this happen?
This is because when the i=1 is satisfied, the first Tang is removed, and the second Tang is moved to the position of the first Tang, that is, cursor 1 corresponds to the second Tang.
Then traverse the i=2 and skip the second tang.
3. Use for reverse traversal Delete, the code is as follows:
for (int i = stulist.count-1; i>=0; i--) { if (stulist[i]. Name = = "Tang") Stulist.remove (Stulist[i]); }
Results:
At this time, all students named Tang were removed.
C # A way to traverse the list and delete one or several elements