msarchet msarchet - 2 years ago 94 Question

Default Object being modified because of LINQ Query

I'm doing the following code to filter a list of objects before it gets sent off to be printed.

Dim printList As New List(Of dispillPatient)
For Each pat As dispillPatient In patList
If (From meds In pat.Medication Select meds Where meds.Print = True).Count > 0 Then
Dim patAdd As New dispillPatient
patAdd = pat
patAdd.Medication = DirectCast((From meds In pat.Medication Select meds Where meds.Print = True).ToList, List(Of dispillMedication))
End If

What is happening is
, which is my initial list, for every
inside of it, that specific patients Medication object (which is another list), is being shorten to the list that is returned to the

I think this has something to do with both the way that .NET makes the copy of my
object when I do
patAdd = pat
and the LINQ query that I'm using. Has anyone had a similar issue before and\or what can I do to keep my initial list from getting truncated.

Answer Source

Assuming that the object represented by pat is a Class, then the object does NOT get copied when you assign it to patAdd, only the reference to the object gets copied so you now have two references to the same object.

If you want to create a copy of the object, you'll need to write your own Copy method which does this manually, then write something like patAdd = pat.Copy().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download