如何在遍历泛型列表时从泛型列表中删除元素?我在找一个更好的花纹为了处理每个需要处理的元素列表,然后根据结果从列表中删除。你不能用.Remove(element)在一个foreach (var element in X)(因为它会导致Collection was modified; enumeration operation may not execute.例外).。你也不能用for (int i = 0; i < elements.Count(); i++)和.RemoveAt(i)因为它会破坏集合中当前相对于i.有什么好办法吗?
3 回答
慕虎7371278
TA贡献1802条经验 获得超4个赞
for (int i = safePendingList.Count - 1; i >= 0; i--){ // some code // safePendingList.RemoveAt(i);}
var list = new List<int>(Enumerable.Range(1, 10));for (int i = list.Count - 1; i >= 0; i--){ if (list[i] > 5) list.RemoveAt(i);}list.ForEach(i => Console.WriteLine(i));
safePendingList.RemoveAll(item => item.Value == someValue);
var list = new List<int>(Enumerable.Range(1, 10));Console.WriteLine("Before:");list.ForEach(i => Console.WriteLine(i)); list.RemoveAll(i => i > 5);Console.WriteLine("After:");list.ForEach(i => Console.WriteLine(i));
慕斯王
TA贡献1864条经验 获得超2个赞
ICollection<int> test = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10});foreach (int myInt in test.Reverse<int>()){ if (myInt % 2 == 0) { test.Remove(myInt); }}
- 3 回答
- 0 关注
- 719 浏览
添加回答
举报
0/150
提交
取消