C#实现在foreach中删除集合中的元素

本文介绍了一种在C#中使用自定义类和IEnumerator接口实现foreach遍历同时安全删除集合元素的方法。通过实例展示了如何避免集合修改异常。

C#实现在foreach中删除集合中的元素

1
2
3
4
5
6
7
8
List< string > str =  new  List< string >();
str.Add(  "zs" );
str.Add( "ls" );
str.Add(  "ws"  );
foreach ( string  in  str)
{
    str.Remove(s);
}

有时候我们在foreach中需要修改或者删除集合

可是这时候却报如下错误:集合已修改;可能无法执行枚举操作。

其实我们简单实现以下就可以实现这个功能

直接上代码如下

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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
public  class  MyClass<T>
{
     MyClassCollection<T> collection =  new  MyClassCollection<T>();
     public  IEnumerator GetEnumerator()
     {
         return  collection;
     }
     public  void  Remove(T t)
     {
         collection.Remove(t);
     }
 
     public  void  Add(T t)
     {
         collection.Add(t);
     }
}
 
public  class  MyClassCollection<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  MyItem
{
     public  string  id
     {
         get ;
         set ;
     }
 
     public  int  sex
     {
         get ;
         set ;
     }
     public  string  name
     {
         get ;
         set ;
     }
 
     public  int  age
     {
         get ;
         set ;
     }
}

  然后我们直接调用一下试验下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
MyClass<MyItem> myclass =  new  MyClass<MyItem>();
//添加10条数据
Random rd =  new  Random();
for  ( int  i = 0; i < 10; i++)
{
     MyItem item =  new  MyItem();
     item.age = rd.Next(1, 80);
     item.id = rd.Next().ToString();
     item.name =  "name"  + rd.Next().ToString();
     item.sex = rd.Next(0, 1);
     myclass.Add(item);
}
 
foreach  (MyItem item  in  myclass)
{
     Console.WriteLine(item.name);
     myclass.Remove(item);
}
 
Console.Read();

  这段代码就是模拟10条数据 输出信息后直接删除

哈哈  是不是很简单呢?当然要实现修改或者其他的功能也是类似的

另外IEnumerator接口中的  public  object Current 为引用类型 所以 如果这里MyItem如果修改为基本类型的话肯定会出现拆箱装箱

如果 如果foreach中是基本类型的话就不要用foreach了 如果需要考虑性能的话。

 源代码下载:https://files.cnblogs.com/files/devgis/TestIEnumerator.rar

<think>我们正在讨论C#中的List<T>和foreach循环。根据用户的问题,他们想了解如何使用以及背后的实现原理。 首先,我们需要解释List<T>是什么,以及foreach循环的基本用法。 然后,我们可以深入探讨foreach循环的实现原理,包括它如何依赖于IEnumerable和IEnumerator接口。 注意:在foreach循环中,我们不能修改集合(如添加或删除元素),否则会抛出InvalidOperationException。这一点在引用[1]中已经提到。 另外,用户可能对性能或其他相关主题感兴趣,因此我们可以生成一些问题。 我们将按照以下结构回答: 1. List<T>的简单介绍 2. foreach循环的基本用法 3. foreach循环的实现原理(包括IEnumerable和IEnumerator) 4. 注意事项(如在foreach中修改集合的问题) 5. 示例代码 6. 生成相关问题 注意:用户要求使用中文回答,并且所有行内数学表达式用$...$,独立公式用$$...$$(但本问题可能不涉及数学公式,所以可能不需要)。</think>### C# List<T> 与 foreach 循环的使用方法及实现原理 #### 1. **List<T> 基础** - **定义**:`List<T>` 是泛型集合,用于动态存储和管理一组类型相同的对象,支持自动扩容。 - **创建**:`List<int> numbers = new List<int>();` - **常用操作**: - 添加元素:`numbers.Add(1);` - 访问元素:`int x = numbers[0];` - 删除元素:`numbers.RemoveAt(0);` #### 2. **foreach 循环基本用法** ```csharp List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" }; foreach (string fruit in fruits) { Console.WriteLine(fruit); // 输出每个元素 } ``` - **语法**:`foreach (var item in collection) { ... }` - **特点**: - 只读遍历:循环变量 `fruit` 是只读的,不能修改集合元素[^1]。 - 自动迭代:无需手动控制索引或迭代器。 #### 3. **实现原理** - **依赖接口**: - `IEnumerable<T>`:集合实现此接口以支持迭代。 - `IEnumerator<T>`:提供迭代过程中的状态管理(如 `Current`、`MoveNext()`)。 - **编译器转换**: ```csharp // foreach 代码实际被转换为: IEnumerator<string> enumerator = fruits.GetEnumerator(); try { while (enumerator.MoveNext()) { string fruit = enumerator.Current; Console.WriteLine(fruit); } } finally { enumerator?.Dispose(); } ``` #### 4. **重要注意事项** 1. **禁止修改集合**: 在 `foreach` 中调用 `Add()`、`Remove()` 或 `Insert()` 会抛出 `InvalidOperationException`[^1]。 ```csharp foreach (var item in fruits) { fruits.Remove(item); // ❌ 运行时异常! } ``` 2. **性能优化**: - 对数组或 `List<T>`,编译器会优化为类似 `for` 循环的索引访问。 - 值类型集合避免装箱:使用 `List<int>` 而非 `ArrayList`。 #### 5. **完整示例** ```csharp using System; using System.Collections.Generic; class Program { static void Main() { List<Person> people = new List<Person> { new Person("Alice", 30), new Person("Bob", 25) }; // foreach 遍历 foreach (Person p in people) { Console.WriteLine($"{p.Name} is {p.Age} years old."); } // 错误示例(修改集合) // foreach (var p in people) { // people.Add(new Person("Charlie", 40)); // ❌ 抛出异常 // } } } class Person { public string Name { get; set; } public int Age { get; set; } public Person(string name, int age) => (Name, Age) = (name, age); } ``` #### 6. **替代方案** - 需修改集合时,改用 `for` 循环或临时集合: ```csharp for (int i = 0; i < fruits.Count; i++) { if (fruits[i] == "Banana") fruits.RemoveAt(i--); // 安全删除 } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值