Reputation: 1100
I am using the Enumerable.Select() method to create a new IEnumerable list from an existing list. Here is the code example:
class ClassA
{
IEnumerable<TypeA> List1;
....
}
class ClassB
{
IEnumerable<TypeB> List2;
...
}
class TypeA
{
//some properties;
IEnumerable<TypeC> Prop3;
}
class TypeB
{
//some properties;
IEnumerable<TypeC> Property3;
}
.
.
.
.
ClassA input; //input data object
ClassB result = new classB();
result.List2 = input.List1.Select(s =>
{
new TypeB()
{
Property1 = s.Prop1,
Property2 = s.Prop2,
Property3 = s.Prop3==null?null:s.Prop3.Select(c=>c)
}
});
In the above example, will List2 be a deep copy or shallow copy of List1? How do I get a deep copy if not?
Also, if I set Prop3 = null AFTER the above code has executed (after result object is created), the result.Property3 also becomes null. Can someone explain why this is happening?
Upvotes: 0
Views: 1081
Reputation: 50245
In the above example, will List2 be a deep copy or shallow copy of List1?
Technically neither because the IEnumerable hasn't been enumerated. This also applies the the Property3
value as well. Once enumerated, it appears that it would be a deep copy.
If I set Prop3 = null AFTER the above code has executed (after result object is created), the result.Property3 also becomes null.
This is because you are likely enumerating result.List2
after setting Prop3 = null. This is entirely based on an apparent misunderstanding of what Select
actually does -- it does not create the new collection upon the line executing but rather instructions on how to create such a collection when ToList
, ToArray
, foreach(var x in y)
, etc. are called (ie, whenever it is enumerated).
Upvotes: 1
Reputation: 4164
The call to Select() doesn't actually cause s.Prop3 to be enumerated at the point it's used, rather you can think of it like a view onto s.Prop3 so that later, when you access Property3, it will enumerate s.Prop3 at that point.
If you want to copy the contents of s.Prop3 when you assign it to Property3, use:
s.Prop3.ToList()
...instead. This copies s.Prop3, element-by-element, into a new list, meaning that if s.Prop3 is modified later, it will have no effect on Property3.
Upvotes: 2