將集合項複製到 .NET 中的另一個集合 (Copy collection items to another collection in .NET)


問題描述

將集合項複製到 .NET 中的另一個集合 (Copy collection items to another collection in .NET)

在 .NET (VB) 中,如何獲取一個集合中的所有項目,並將它們添加到第二個集合中(而不會丟失第二個集合中預先存在的項目)?我正在尋找比這更高效的東西:

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

我的集合是通用集合,繼承自基類 ‑‑ Collection(Of )


參考解法

方法 1:

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

方法 2:

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.

方法 3:

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.

方法 4:

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

方法 5:

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.

(by Matt HansonjopBen HoffsteinDavid RobbinsjohncKangkan)

參考文件

  1. Copy collection items to another collection in .NET (CC BY‑SA 2.5/3.0/4.0)

#collections #vb.net #.net






相關問題

C ++中集合/容器的接口/超類 (Interface/Superclass for Collections/Containers in c++)

如何將對象列表轉換為兩級字典? (How to convert a list of objects to two level dictionary?)

如何在java中限制哈希集的默認排序 (how to restrict default ordering of Hash Set in java)

將兩個單獨的 Set 轉換為二維數組 (Convert two separate Sets to a 2D array)

事件調度線程從列表異常 SWING 中移除 (Event dispatching thread remove from List exception SWING)

將集合項複製到 .NET 中的另一個集合 (Copy collection items to another collection in .NET)

java - 如何在java中使用某些特定索引將值存儲到arraylist中 (how to store value into arraylist with some specific index in java)

將對象添加到具有主幹的第一個位置的集合中? (Adding object to a Collection in the first position with backbone?)

在VB中過濾一個wpf collectionviewsource? (Filter a wpf collectionviewsource in VB?)

將流式數據讀入排序列表 (Reading streamed data into a sorted list)

有沒有一種自動處理數組和強類型集合之間轉換的好方法? (Is there a good way to handle conversions between arrays and strongly typed collections automatically?)

將數據行轉換為 1 個對象 (Convert data rows to 1 object)







留言討論