将集合转换为数组的最优化/有效方法?

时间:2010-07-06 16:47:12

标签: c# vb.net arrays collections .net-2.0

我知道它必须被问过两次以上,但我找不到任何适用的问题来回答这个问题。

我有一个集合,我希望从.NET 2.0中检索一个数组。换句话说,我想将一个集合转换为一个数组。到目前为止,我有以下内容:

Public Class Set(Of T)
    Implements IEnumerable(Of T)
    Implements ICollection(Of T)
    Implements IEqualityComparer(Of T)

    Private _set as Dictionary(Of T, Object)

    // Implementing the interfaces here...

    Public Function ToArray() As Array
        Dim arr As Array = Array.CreateInstance(GetType(T), Me.Count)
        Me.CopyTo(arr, 0)
        Return arr
    End Function
End Class

然后,当我打电话时,我只需要:

Dim propertiesToLoad As CustomSet(Of String) = New CustomSet(Of String)()
// Initializing my CustomSet here...

Dim searcher As DirectorySearcher = New DirectorySearcher()
Dim entry As DirectoryEntry = New DirectoryEntry("LDAP://" & Environment.UserDomain)

searcher.SearchRoot = entry
searcher.SearchScope = SearchScope.Subtree
searcher.Filter = someFilter
searcher.PropertiesToLoad.AddRange(propertiesToLoad.ToArray())

// Launching search here...

在.NET 2.0中有更有效的方法吗?

编辑#1

我的CustomSet(Of T)中Count和CopyTo的实现:

Public ReadOnly Property Count As Integer Implements ICollection(Of T).Count
    Get
        Return _set.Keys.Count
    End Get
End Property

Public Sub CopyTo(ByVal array As T, ByVal arrayIndex As Integer) Implements ICollection(Of T).CopyTo
    _set.Keys.CopyTo(array, arrayIndex)
End Sub

2 个答案:

答案 0 :(得分:1)

您应该将AddRange方法更改为IEnumerable<T>ICollection<T>(如果您需要Count)。
这样,您根本不需要调用ToArray,从而节省了内存分配。

您的实施看起来很好 但请注意,Dictionary<TKey, TValue>是无序的。

答案 1 :(得分:1)

您不需要使用CreateInstance来创建数组,您知道类型,甚至可以将其作为特定类型的数组返回:

Public Function ToArray() As T()
  Dim arr(Me.Count) As T
  Me.CopyTo(arr, 0)
  Return arr
End Function

这有多高效,当然取决于ICollection(Of T).CountICollection(Of T).CopyTo的实施效率。