且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-08-20 19:51:57

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中需要修改或者删除集合

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

C#实现在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条数据 输出信息后直接删除

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

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

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

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

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