views:

4666

answers:

9

In .NET (VB), how can I take all of the items in one collection, and add them to a second collection (without losing pre-existing items in the second collection)? I'm looking for something a little more efficient than this:

For Each item As Host In hostCollection1
    hostCollection2.Add(item)
Next

My collections are generic collections, inherited from the base class -- Collection(Of )

+1  A: 

I know you're asking for VB, but in C# you can just use the constructor of the collection to initialize it with any IEnumerable. For example:

List<string> list1 = new List<string>();
list1.Add("Hello");
List<string> list2 = new List<string>(list1);

Perhaps the same kind of thing exists in VB.

Ben Hoffstein
But will pre-existing items in list2 be lost? I'm trying to add to the second collection, not exactly duplicate the first collection.
Matt Hanson
Oh sorry, I misunderstood. In that case, I would use the AddRange method on my list2 object.
Ben Hoffstein
You just added to your post that you are using the base Collection class. In this case, none of the AddRange solutions are going to work. If you are using .NET 3.5, we could go the extension method route...
Ben Hoffstein
I am using 3.5, but I didn't even know about extension methods. I don't think it's the route I'm going to take, but definitely pretty cool! Thanks!
Matt Hanson
A: 

Array.Copy may solve your problem.

A: 

List.CopyTo(T[]); maybe?

http://msdn.microsoft.com/en-us/library/t69dktcd.aspx

Slace
+1  A: 

Ben's solution does exist for VB.Net:

Dim collection As IEnumerable(Of T)    
Dim instance As New List(collection)

Here is the linked documentation.

However, one thing I would be concerned with is whether or not it does a shallow copy or a deep copy.

Austin Salonen
+1  A: 

Don't forget that you will be getting a reference and not a copy if you initialize your List2 to List1. You will still have one set of strings unless you do a deep clone.

David Robbins
+14  A: 

You can use AddRange: hostCollection2.AddRange(hostCollection1).

jop
A: 

I always use the List<T>.AddRange(otherList<T>) function. Again, if this is a list of objects, they will be references the same thing.

You have not specified what sort of collection though, AddRange doesn't exist in CollectionBase inherited objects

johnc
A: 

Hi Matt,

Unless you want both collections to modify the same set of objects, then each object is going to have to be copied to the Heap. Maybe you can describe your scenario of how this is impacting your performance and we can find a good solution.

Cory Foy
A: 

This is available when one use an IList. But AddRange method is not available in Collection. I thought of casting Collection to List, but it is not possible.

Regards, Kangkan

Kangkan