1.首先在该命名空间下创建一个实体,和在Main方法下List集合,为后续做准备:
/// <summary> /// 实体 /// </summary> public class Student { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } public string Location { get; set; } public string Hobby { get; set; } }
//创建一个List集合 List<Student> Students = new List<Student>(); //添加数据 Students.Add(new Student() { ID=1, Name="猪猪侠", Age=12, Location="长沙", Hobby = "打怪" }); Students.Add(new Student() { ID = 2, Name = "猫咪", Age = 15, Location = "株洲", Hobby = "打球" }); Students.Add(new Student() { ID = 3, Name = "大象", Age = 34, Location = "邵阳", Hobby = "抽血" }); Students.Add(new Student() { ID = 4, Name = "猴子", Age = 32, Location = "醴陵", Hobby = "吃香蕉" }); Students.Add(new Student() { ID = 5, Name = "鸭子", Age = 30, Location = "山西", Hobby = "吃蚯蚓" });
一、【错误演示】:有很多人会使用遍历,但是顺序遍历会导致删除不完整
for (int i = 0; i <= Students.Count; i++) { Students.Remove(Students[i]); //Students.RemoveAt(i); //Students.RemoveRange(i, 1); } foreach (var item in Students) { Console.WriteLine($"ID:{item.ID}--Name:{item.Name}--Age:{item.Age}--Location:{item.Location}--Hpbby:{item.Hobby}"); }//没有按照预想的删除完成
二、【正确演示】:使用倒序遍历
//【正确演示】 for (int i = Students.Count-1; i >= 0; i--) { Students.Remove(Students[i]); } foreach (var item in Students) { Console.WriteLine($"ID:{item.ID}--Name:{item.Name}--Age:{item.Age}--Location:{item.Location}--Hpbby:{item.Hobby}"); }//能看到完全删除了