C#实现在foreach遍历中删除集合中的元素(方法总结)
在foreach中删除元素时,每一次删除都会导致集合的大小和元素索引值发生变化,从而导致在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);
}
}
}
C#实现在foreach遍历中删除集合中的元素(方法总结)的更多相关文章
- C#实现在foreach中删除集合中的元素
List<string> str = new List<string>(); str.Add( "zs"); str.Add("ls") ...
- C#中删除集合中符合条件的元素以及需注意属相
如果用foreach,会造成被遍历的集合更改后带来异常问题. 此时,用for循环可有效的解决这个问题. for(int i=0;i<List.Count;i++) { if(条件是真) { Li ...
- 使用Properties集合存储数据,遍历取出Properties集合中的数据和Properties集合中的方法store和load
package com.yang.Test.PropertiesStudy; import java.io.FileWriter; import java.io.IOException; import ...
- Day_11【集合】扩展案例2_使用普通for循环获取集合中索引为3的元素并打印,统计集合中包含字符串"def"的数量,删除集合中的所有字符串",将集合中每个元素中的小写字母变成大写字母def",
分析以下需求,并用代码实现 1.定义ArrayList集合,存入多个字符串"abc" "def" "efg" "def" ...
- Java循环删除集合多个元素的正确打开方式
首先说下不正确的打开方式: 第一:使用for循环删除集合的元素,示例代码如下 ArrayList<String> list = new ArrayList<String>(Ar ...
- ArcGIS Engine中删除要素的几种方法总结
转自原文 ArcGIS Engine中删除要素的几种方法总结 /// <summary> /// 通过IFeature.Delete方法删除要素 /// </summary> ...
- 【转载】C#中List集合中Last和LastOrDefault方法的差别
在C#的List集合操作中,Last方法和LastOrDefault方法都会用来查找集合中最后一个符合条件的元素对象,但Last和LastOrDefault方法还是有差别的,建议使用LastOrDef ...
- 【转载】C#中List集合SingleOrDefault和FirstOrDefault方法有何不同
在C#的List集合类的操作过程中,有时候我们会使用到List集合的SingleOrDefault方法和FirstOrDefault等方法,这2个方法都是System.Linq.Enumerable类 ...
- 【转载】C#中List集合First和FirstOrDefault方法有何不同
在C#的List集合中查找一个符合条件的元素,一般我们会用First方法或者FirstOrDefault方法来返回第一个符合条件的对象,First方法和FirstOrDefault的调用都是使用Lam ...
随机推荐
- 产品分析:华为短信APP体验的问题和建议
- 微擎签名出错 invalid signature
微擎签名出错 错误信息: config:fail,Error: 系统错误,错误码:63002,invalid signature 修改方法: PHP 端 $account_api = WeAccoun ...
- Ocelot学习笔记
最近因工作需要,开始学习Ocelot.首先简单介绍一下,Ocelot是一个基于.net core的开源webapi 服务网关项目,目前已经支持了IdentityServer认证.根据 作者介绍,Oce ...
- [转发]CSR 量产 烧录 软件
蓝牙量产软件主要是为了应对蓝牙设备在批量生产时的一些如固件下载,地址下载,名字修改,以及一些辅助测试和检验功能. 目前,CSR推出的蓝牙芯片按照存储介质以及可编程与否分为两大类:ROM版本和Flash ...
- ubuntu 16.04 和 windows 10系统安装mysql 允许远程访问 | mysql user guide on ubuntu 16.04 and windows 10
本文首发于个人博客https://kezunlin.me/post/36e618e7/,欢迎阅读! mysql user guide on ubuntu 16.04 and windows 10 Pa ...
- 20191010-7 alpha week 1/2 Scrum立会报告+燃尽图 05
此作业要求参见:https://edu.cnblogs.com/campus/nenu/2019fall/homework/8750 一.小组情况 队名:扛把子 组长:迟俊文 组员:宋晓丽 梁梦瑶 韩 ...
- vue 中 keep-alive 缓存数据、离开时位置
路由中: 页面中: 需要缓存的组件中: 因为是keep-alive 所以在初始化页面的时候 会走一次生命周期 当二次进入的时候就已经是缓存状态了 不会在走生命周期 于是它就有了自己的周期函数分别是 ...
- 剑指Offer-32.丑数(C++/Java)
题目: 把只包含质因子2.3和5的数称作丑数(Ugly Number).例如6.8都是丑数,但14不是,因为它包含质因子7. 习惯上我们把1当做是第一个丑数.求按从小到大的顺序的第N个丑数. 分析: ...
- android clipChildren 的使用与遇到的困难
案例 在一次我写画板模块的时候,布局比较普通,但是需要子元素溢出父元素.其中一小块布局如下所示: 红色部分需要溢出,这个时候我想到了clipChildren. clipChildren 就是说我可以不 ...
- 【开发工具 - MySQL】之不能插入中文的问题
新安装的MySQL数据库,在安装的时候设置了字体为UTF8,但在使用insert语句插入中文的时候还是会报错. 具体解决方法:在MySQL控制台中输入以下设置代码: SET character_set ...
