C#在foreach遍历删除集合中元素的三种实现方法

作者:willingtolove 时间:2022-05-28 12:22:50 

前言

在foreach中删除元素时,每一次删除都会导致集合的大小和元素索引值发生变化,从而导致在foreach中删除元素时会抛出异常。

集合已修改;可能无法执行枚举操作。

C#在foreach遍历删除集合中元素的三种实现方法

方法一:采用for循环,并且从尾到头遍历

如果从头到尾正序遍历删除的话,有些符合删除条件的元素会成为漏网之鱼;

正序删除举例:


List<string> tempList = new List<string>() { "a","b","b","c" };

for (int i = 0; i < tempList.Count; i++)
{
 if (tempList[i] == "b")
 {
  tempList.Remove(tempList[i]);
 }
}

tempList.ForEach(p => {
 Console.Write(p+",");
});

控制台输出结果:a,b,b,c

有两个2没有删除掉;

这是因为当i=1时,满足条件执行删除操作,会移除第一个b,接着第二个b会前移到第一个b的位置,即游标1对应的是第二个b。

接着遍历i=2,也就跳过第二个b。

用for倒序遍历删除,从尾到头


List<string> tempList = new List<string>() { "a","b","b","c" };

for (int i = tempList.Count-1; i>=0; i--)
{
 if (tempList[i] == "b")
 {
  tempList.Remove(tempList[i]);
 }
}

tempList.ForEach(p => {
 Console.Write(p+",");
});

控制台输出结果:a,c,

这次删除了所有的b;

方法二:使用递归

使用递归,每次删除以后都从新foreach,就不存在这个问题了;


static void Main(string[] args)
{
 List<string> tempList = new List<string>() { "a","b","b","c" };
 RemoveTest(tempList);

tempList.ForEach(p => {
  Console.Write(p+",");
 });
}
static void RemoveTest(List<string> list)
{
 foreach (var item in list)
 {
  if (item == "b")
  {
   list.Remove(item);
   RemoveTest(list);
   return;
  }
 }
}

控制台输出结果:a,c,

正确,但是每次都要封装函数,通用性不强;

方法三:通过泛型类实现IEnumerator


static void Main(string[] args)
{
 RemoveClass<Group> tempList = new RemoveClass<Group>();
 tempList.Add(new Group() { id = 1,name="Group1" }) ;
 tempList.Add(new Group() { id = 2, name = "Group2" });
 tempList.Add(new Group() { id = 2, name = "Group2" });
 tempList.Add(new Group() { id = 3, name = "Group3" });

foreach (Group item in tempList)
 {
  if (item.id==2)
  {
   tempList.Remove(item);
  }
 }

foreach (Group item in tempList)
 {
  Console.Write(item.id+",");
 }
//控制台输出结果:1,3

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);
  }
 }
}

来源:https://www.cnblogs.com/willingtolove/p/12051649.html

标签:foreach,遍历,集合
0
投稿

猜你喜欢

  • C# Timer控件学习之使用Timer解决按钮幂等性问题

    2021-07-07 11:26:09
  • C#使用CefSharp实现内嵌网页详解

    2022-04-12 15:02:00
  • MyBatis-Plus中更新操作的两种实现

    2022-06-24 03:09:14
  • springcloud feign传输List的坑及解决

    2023-06-20 18:31:57
  • java协程框架quasar和kotlin中的协程对比分析

    2021-06-25 23:22:05
  • Spring+MyBatis实现数据读写分离的实例代码

    2021-08-31 04:34:48
  • JAVA操作MongoDB数据库实例教程

    2023-11-18 13:22:27
  • C#通过标签软件Bartender的ZPL命令打印条码

    2022-05-22 01:30:40
  • Android 屏幕截屏方法汇总

    2022-01-23 05:48:18
  • Java Spring AOP源码解析之事务实现原理

    2023-09-10 02:39:46
  • java寻找迷宫路径的简单实现示例

    2021-07-06 13:17:50
  • java实现zip,gzip,7z,zlib格式的压缩打包

    2023-08-13 08:56:59
  • 运行java的class文件方法详解

    2021-07-29 03:53:48
  • C#利用VS中插件打包并发布winfrom程序

    2022-01-01 21:18:22
  • 关于springcloud集成nacos遇到的问题

    2022-02-27 17:41:46
  • HashMap红黑树入门(实现一个简单的红黑树)

    2022-10-18 13:52:35
  • java中this的n种使用方法

    2023-12-23 13:13:23
  • Redis使用RedisTemplate模板类的常用操作方式

    2023-01-30 08:33:40
  • java如何用Processing生成马赛克风格的图像

    2023-11-07 20:52:44
  • JAVA进程突然消失问题解决方案

    2023-12-24 04:38:43
  • asp之家 软件编程 m.aspxhome.com