Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
4.67/5 (3 votes)
See more:
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>


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();


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?
Posted
Comments
Pravin Patil, Mumbai 26-Jan-11 5:01am    
Very good question danish.
shakil0304003 26-Jan-11 5:31am    
Good point!!!
Sergey Alexandrovich Kryukov 26-Jan-11 15:20pm    
Good catch! - a 5.
--SA

1 solution

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.
 
Share this answer
 
Comments
#realJSOP 26-Jan-11 7:28am    
Proposed as answer.
Sergey Alexandrovich Kryukov 26-Jan-11 15:19pm    
Very good, my 5.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900