从集合中删除在foreach循环中迭代的项目 [英] Removing an item from collection which is iterated in foreach loop

查看:156
本文介绍了从集合中删除在foreach循环中迭代的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查以下代码:

Check the code below:

class Program
    {
        class TestClass
        {
            public int MyProperty { get; set; }

            public int MyProperty1 { get; set; }
        }

        static void Main(string[] args)
        {
            Collection<testclass> testCollection = new Collection<testclass>();
            testCollection.Add(new TestClass());
            testCollection.Add(new TestClass());
            
            var test = (from str in testCollection
                        select new {p1 = str.MyProperty, p2 = str.MyProperty1});

            foreach (var item in test)
            {
                testCollection.Remove(testCollection.Where(x => x.MyProperty1 == item.p2).First());
            }
        }
    }</testclass></testclass>



当第二次执行循环时,它将引发InvalidOperationException.现在只需更改LINQ表达式,如下所示:



It throws InvalidOperationException when the loop is executed for the second time. Now just change the LINQ expression as below:

var test = (from str in testCollection
            select new {p1 = str.MyProperty, p2 = str.MyProperty1}).ToList();



有用!我的假设是ToList方法在转换返回类型之前会创建一个深层副本,因此它可以工作.看来我的假设是正确的,因为在调试时,当我从集合中删除项目时,可以看到变量test保持不变.有人可以确认吗?还是我完全走错了路?



It works! My assumption is that ToList method creates a deep copy before converting the return types and hence it works. It looks like my assumption is correct since when I debug, I can see that the variable test is unchanged when I remove the item from the collection. Can someone confirm? Or I am totally on a wrong track?

推荐答案

您非常正确-ToList方法遍历LINQ select的结果,并将其存储到列表中(严格来说,它不是深层副本",但我想那是您的意思).如果您不调用toList或ToArray,则由于您的foreach循环遍历可枚举的测试,LINQ会继续遍历testCollection.这就是为什么它在第二次迭代中遇到异常-不允许修改正在迭代的集合.
You are very much correct - ToList method iterates over the results of your LINQ select, and stores them into a list (strictly speaking, it''s not a "deep copy", but I guess that''s what you meant). If you do not call toList or ToArray, LINQ continues to iterate over testCollection as your foreach loop iterates over the test enumerable. That''s why it hits an exception on the second iteration - modifying a collection being iterated is not allowed.


这篇关于从集合中删除在foreach循环中迭代的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆