How to make copy of collection object?

S

Sakharam Phapale

Hi All,

eg. "Array.Copy" method used to copy array elements.

Is there any method to copy collection objects data,
except iterating through original collection and then filling each element
into other collection, which is a lengthy process.

colBackupEmp = m_colEmp
Above statement sets the reference.
---------------------------------------------------------------------

Structure Employee
Dim ID As Integer
Dim Name As String
End Structure

Private m_colEmp As New Collection
Private m_colBackupEmp As New Collection

Private Sub LoadEmployee()
Dim Emp as Employee
Emp.ID = 100
Emp.Name = "John"
m_colEmp.Add (Emp)

Emp.ID = 200
Emp.Name = "Sam"
m_colEmp.Add (Emp)
End Sub


Private Sub BackupEmployeeData()
''''''' colBackupEmp = m_colEmp ''''''''
Dim Emp As Employee
For Each Emp In m_colEmp
m_colBackupEmp.Add (Emp)
Next
End Sub
 
N

Nicholas Paldino [.NET/C# MVP]

Sakharam,

There really isn't, since the collection wouldn't know exactly what
needs to be copied. Most of the time, collections are of reference types
(just an observation) which don't have natural copy semantics. It's because
of this that I assume there is nothing native in the collection to copy it
to another collection of the same type.

You will have to implement this yourself.

Hope this helps.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

Assuming that you mean classes derived from CollectionBase the answer is
not, this does not prevent you of creating a method that do that, though.

A final remark, this is a C# group, the code you provided is VB.net

Cheers,
 
M

Mortimer Schnurd

Consider using a serializable class instead of a VB Collection object
(which is not serializable). Have that class implement ICloneable and
implement the Clone method of that interface. In the Clone method you
will need to use a BinaryFormatter.Serialize to serialize your class
(Me) into a MemoryStream. You would then return a
BinaryFormatter.DeSerialize object from the Clone method.
This will give you a "deep" copy of your class, which is what I think
you are striving for. My suggestion involves a little more coding but
if your are planning to work on a very large collection I believe the
processing time will not be as "lengthy" as using a For Each iteration.
I don't have any timings I can use to prove it, this is just a guess.
HTH,
JW
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top