foreach中使用Remove和Add_mst
1.删除第二个数据时开始报错,因为list长度发生了变化,会报错
List<string> list = new List<string>() { "a","b","c","d","e","f","g","h"}; Console.WriteLine("加入数据长度:" + list.Count.ToString()); foreach (var item in list) { //list.Remove(item); Console.WriteLine("Remove的数据:" + item); } Console.WriteLine("Remove后的数据长度:" + list.Count.ToString());
2.解决方法:
2.1 for 倒叙遍历删除
//构造list List<string> tempList = new List<string>() { "a", "b", "c", "d" }; //打印现有list tempList.ForEach(p => { Console.WriteLine("tempList中的数据:" + p + ","); }); //删除list数据,必须倒叙,正序可能会导致删除不完全 for (int i = tempList.Count - 1; i >= 0; i--) { //删除所有 tempList.Remove(tempList[i]); //删除 b //if (tempList[i] == "b") //{ // tempList.Remove(tempList[i]); //} } //打印剩余list数据 tempList.ForEach(p => { Console.WriteLine("tempList剩余数据:" + p + ","); });
2.2 递归 原理是删除后重新读取list 这样就不会因为长度变化而报错
List<string> tempList1 = new List<string>() { "a", "b", "c", "d", "c", "f", "g", "c", "m" }; RemoveTest(tempList1); tempList1.ForEach(p => { Console.WriteLine("使用递归删除c,剩余:" + p + ","); }); //递归方法 static void RemoveTest(List<string> list) { foreach (var item in list) { if (item == "c") { list.Remove(item); RemoveTest(list); return; } } }
2.3 用泛型IEnumerator
RemoveClass<Groups> tempListie = new RemoveClass<Groups>(); tempListie.Add(new Groups() { id = 1, name = "Group1" }); tempListie.Add(new Groups() { id = 2, name = "Group2" }); tempListie.Add(new Groups() { id = 2, name = "Group2" }); tempListie.Add(new Groups() { id = 3, name = "Group3" }); foreach (Groups item in tempListie) { if (item.id == 2) { tempListie.Remove(item); } }
2.3.1 新建一个接口类 RemoveClass.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Zoo { public class RemoveClass<T> { RemoveClassCollection<T> collection = new RemoveClassCollection<T>(); public IEnumerator GetEnumerator() { return collection; } public void Remove(T t) { collection.Remove(t); } public void Add(T t) { collection.Add(t); } } public class RemoveClassCollection<T> : IEnumerator { List<T> list = new List<T>(); public object current = null; Random rd = new Random(); public object Current { get { return current; } } int icout = 0; public bool MoveNext() { if (icout >= list.Count) { return false; } else { current = list[icout]; icout++; return true; } } public void Reset() { icout = 0; } public void Add(T t) { list.Add(t); } public void Remove(T t) { if (list.Contains(t)) { if (list.IndexOf(t) <= icout) { icout--; } list.Remove(t); } } } public class Groups { public int id { get; set; } public string name { get; set; } } }

浙公网安备 33010602011771号