tags:

views:

41

answers:

3

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.

Thanks

+2  A: 

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

Greg Beech
that makes sense, thanks.
msarchet
silly answer timer
msarchet
+2  A: 
patAdd = pat

This is your problem. This does not create a copy of your pat instance, this simply makes your patAdd variable point to the same instance as the pat variable.

In order to do this, you'll have to create a new dispillPatient object based upon pat and store that instance in patAdd.

While there's no particular idiom defined for doing this, some common ways are copy constructors:

Public Sub New(source as dispillPatient)
    ' copy whatever is necessary from source, realizing that any
    ' other reference types -- like lists -- also need to be duplicated
    ' in similar fashion
End Sub

Or a Copy/Clone function

Public Function Clone() As dispillPatient
    Dim output as new dispillPatient

    ' copy whatever is necessary to output, realizing that any
    ' other reference types -- like lists -- also need to be duplicated
    ' in similar fashion

    return output
End Function
Adam Robinson
yes, I don't know why I didn't realize this, I was just sitting going hrmmmm.
msarchet
A: 

This is a reference assignment - no copy is made!

patAdd = pat 

That means that patAdd and pat are one and the same thing!

This modifies patAdd (and since pat is the same thing, it too is modified)

patAdd.Medication = DirectCast((From meds In pat.Medication Select meds Where meds.Print = True).ToList, List(Of dispillMedication))  
David B