Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy collection items to another collection in .NET

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 )

like image 789
Matt Hanson Avatar asked Sep 29 '08 03:09

Matt Hanson


3 Answers

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

like image 116
jop Avatar answered Nov 19 '22 08:11

jop


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.

like image 5
Ben Hoffstein Avatar answered Nov 19 '22 10:11

Ben Hoffstein


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.

like image 3
David Robbins Avatar answered Nov 19 '22 10:11

David Robbins