当我们对集合foreach遍历时,不能直接移除遍历的集合的元素,解决的方法有很多种,见我之前的随笔:
http://www.cnblogs.com/527289276qq/p/4331000.html
除此之外,我今天发现了利用linq中的ToArray()方法,也可以实现遍历集合,移除集合中的元素,代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { List<Person> list = new List<Person> { new Person{Name="张三",Age=17}, new Person{Name="李四",Age=15}, new Person{Name="王五",Age=19}, new Person{Name="赵六",Age=14}, new Person{Name="孙七",Age=18} }; foreach (Person p in list.ToArray()) { if (p.Age < 18) { string name = p.Name; list.Remove(p); Console.WriteLine("删除了{0},list的Count为:{1}!", name, list.Count()); Thread.Sleep(1000); } } Console.WriteLine("移除完毕!"); Console.ReadKey(); } } public class Person { private string name; public string Name { get { return name; } set { name = value; } } private int age; public int Age { get { return age; } set { age = value; } } } }
运行效果如下:
代码很简单,对集合操作有多了一种方法!