c#List移除列表中的元素

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

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             try
 6             {
 7                 List<Student> studentList = new List<Student>();
 8                 for (int i = 0; i < 10; i++)
 9                 {
10                     Student s = new Student()
11                     {
12                         Age = 10,
13                         Name = "John"
14                     };
15                     studentList.Add(s);
16                 }
17                 studentList.Add(new Student("rose",9));
18                 studentList.Add(new Student("rose", 10));
19                 studentList.Add(new Student("rose", 11));
20 
21                22                 31                 40                 //不能用foreach进行删除列表元素的操作,因为这种删除方式破坏了索引
41                 //foreach (var testInt in studentList)
42                 //{
43                 //    if (testInt.Age == 10)
44                 //        studentList.Remove(testInt);
45                 //}
46                 Console.Read();
47             }
48             catch (Exception)
49             {
50 
51                 throw;
52             }
53             
54             
55         }
56     }

方法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 = 0; i < studentList.Count - 1; )
{
    if (studentList[i].Age==10)
    {
        studentList.Remove(studentList[i]);
    }
    else
    { 
        i++;
    }
}

  

方法3:使用RemoveAll筛选移除

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

  

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

原文地址:https://www.cnblogs.com/dst5650/p/5161283.html