msarchet msarchet - 7 months ago 17
Vb.net 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))
printList.Add(patAdd)
End If
Next


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

I think this has something to do with both the way that .NET makes the copy of my
pat
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

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