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循环顺序删除
32                 for (int i = 0; i < studentList.Count - 1; )
33                 {
34                     if (studentList[i].Age==10)
35                     {
36                         studentList.Remove(studentList[i]);
37                     }
38                     i++;
39                 }

  

方法3:使用RemoveAll筛选移除

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

  

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

转载于:https://www.cnblogs.com/dst5650/p/5161283.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值