I have a 2 collection of varying objects.
Let’s say I have the following two objects
Private col1 as Collection(Of A) and Private col2 as Collection(Of B)
But object of Type A has a collection of Type B as an Attribute.
so A looks like that
Public Class A
Public Property myStringProp() as string
Public Property colB() as Collection(Of B)
End Class
whereas B looks like
Public Class B
Public Property myStringProp() as string
End Class
So in col2 i can have e.g. 20 items of Type B.
In col1 I have e.g. 2 items of Type A. Each of them has n references to items of Type B to the collection of col2.
How can I serialize and deserialize these Objects so that the references will be restored when deserializing?
Preferred Serialization with XML.
I have tried to use the DataContractSerializer but I have no idea where and how to use it.
Edit:
OK. I would be able to resolve them manually. But I don’t like the way:
For Each itema As A In col1
For Each itemb As B In itema.colB
For Each objB In col2
If itemb.myStringProp = objB.myStringProp Then
itemb = objB
End If
Next
Next
Next
This would just loop through all objects of A in col1 and then loop through all objects of B and search an object in col2 with the same value for myStringProp.
So any cleaner solution would be appreciated 🙂
So any cleaner solutions?
The serializer can preserve object references in a single serialization episode. So if you have both collections as members of a single object (which is then serialized / deserialized), you can use the
preserveObjectReferencesparameter in theDataContractSerializerconstructor, and you’ll get that. Another option is to decorate the type with<DataContract(IsReference:=True)>, which can also be used to preserve the references. The code below shows the first approach.