C# foreach on IEnumerable vs. List - element modification persistent only for array - Why?

前端 未结 2 1855
独厮守ぢ
独厮守ぢ 2021-01-13 19:55

In C#, I have noticed that if I am running a foreach loop on a LINQ generated IEnumerable collection and try to modify the contents of each T element,

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-13 20:28

    You are right, it is deferred execution. A new MyClass instance is created each time you iterate the IEnumerable. By calling ToList or ToArray you then create a List or Array and populate it with the new MyClass instances created from the iteration of the IEnumerable.

提交回复
热议问题