c#List移除列表中的元素

时间:2022-05-05 03:32:24

对于一个List<T>对象来说移除其中的元素是常用的功能。自己总结了一下,列出自己所知的几种方法。

 class Program
{
static void Main(string[] args)
{
try
{
List<Student> studentList = new List<Student>();
for (int i = ; i < ; i++)
{
Student s = new Student()
{
Age = ,
Name = "John"
};
studentList.Add(s);
}
studentList.Add(new Student("rose",));
studentList.Add(new Student("rose", ));
studentList.Add(new Student("rose", )); //不能用foreach进行删除列表元素的操作,因为这种删除方式破坏了索引
//foreach (var testInt in studentList)
//{
// if (testInt.Age == 10)
// studentList.Remove(testInt);
//}
Console.Read();
}
catch (Exception)
{ throw;
} }
}

方法1:for循环倒序移除

//for循环倒序删除
23 for (int i = studentList.Count - 1; i >= 0; i--)
24 {
25 if (studentList[i].Age == 10)
26 {
27 studentList.Remove(studentList[i]);
28 //studentList.RemoveAt(i);
29 }
30 }

  

方法2:for循环顺序移除//for循环顺序删除

for (int i = ; i < studentList.Count - ; )
{
if (studentList[i].Age==)
{
studentList.Remove(studentList[i]);
}
else
{ 
i++;
}
}

  

方法3:使用RemoveAll筛选移除

 studentList.RemoveAll((test) => test.Age == 10);//可以用此Linq表达式移除所有符合条件的列表元素

  

方法4:克隆所有非移除元素至一个新的列表中