服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#在foreach遍历删除集合中元素的三种实现方法

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

2022-08-11 09:45willingtolove C#

这篇文章主要给大家总结介绍了关于C#在foreach遍历删除集合中元素的实现方法,文中通过示例代码介绍的非常详细,对大家学习或者使用C#具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧

前言

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

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

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

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

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

正序删除举例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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倒序遍历删除,从尾到头

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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,就不存在这个问题了;

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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

延伸 · 阅读

精彩推荐
  • C#C#开发微信门户及应用(4) 关注用户列表及详细信息管理

    C#开发微信门户及应用(4) 关注用户列表及详细信息管理

    这篇文章主要为大家详细介绍了C#开发微信门户及应用第四篇,关注用户列表及详细信息管理,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    伍华聪9652022-01-07
  • C#基于c#用Socket做一个局域网聊天工具

    基于c#用Socket做一个局域网聊天工具

    目前基于Internet的即时聊天工具已经做的非常完美,本文介绍了基于c#用Socket做一个局域网聊天工具,有需要的朋友可以看一下。...

    Create Chen10202021-12-08
  • C#C#导出Excel的示例详解

    C#导出Excel的示例详解

    这篇文章主要为大家详细介绍了C#导出Excel的示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    YellowCool7472022-01-20
  • C#讲解C#面相对象编程中的类与对象的特性与概念

    讲解C#面相对象编程中的类与对象的特性与概念

    这篇文章主要介绍了C#面相对象编程中的类与对象的特性与概念,OOP面向对象语言相对C语言这样面相过程的语言来说具有类和对象以及方法这样的特性,需要...

    C#教程网10472021-11-09
  • C#C#创建数据库及导入sql脚本的方法

    C#创建数据库及导入sql脚本的方法

    这篇文章主要介绍了C#创建数据库及导入sql脚本的方法,涉及C#针对数据库的创建、连接、导入等相关操作技巧,需要的朋友可以参考下...

    思齐_4342021-11-05
  • C#C#读写config配置文件的方法

    C#读写config配置文件的方法

    下面小编就为大家带来一篇C#读写config配置文件的方法。小编觉的挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    C#教程网10912021-12-11
  • C#全面解读C#编程中的析构函数用法

    全面解读C#编程中的析构函数用法

    这篇文章主要介绍了C#编程中的析构函数用法,文中最后还整理了析构函数与Dispose()方法的区别,需要的朋友可以参考下...

    C#教程网7142021-11-09
  • C#大家应该掌握的多线程编程

    大家应该掌握的多线程编程

    这篇文章主要介绍了大家应该掌握的多线程编程,具有一定借鉴价值,需要的朋友可以参考下...

    Helius-黑牛4512022-02-17