我知道它一定被問了兩次以上,但我找不到任何適用的問題來回答這個問題。將集合轉換爲數組的最優化/有效的方法?
我有一個集合,我希望從.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
實現和CopyTo從我CustomSet(Of T)已:
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
那,我不知道如何在VB.NET中做。感謝這個建議!至於Count和CopyTo的實現,請參閱我將在編輯#1中提供的代碼。謝謝! =) – 2010-07-06 17:34:31
@威爾:看起來很有效。如果你直接在字典中循環而不是使用'Keys'集合,那麼稍微改進它可能是可能的,但這很難增加複雜性。 – Guffa 2010-07-06 19:44:20
感謝您的評論和改進痕跡,即使這些由於複雜性而不值得。我很欣賞這些提示。 =) – 2010-07-07 13:08:52