簡體   English   中英

通過 DirectoryServices 在給定字段(例如國家/地區)中查詢 Active Directory 中的不同值

[英]Query Active Directory for distinct values in a given field (e.g. Country) via DirectoryServices

我需要以編程方式檢索 Active Directory 中給定字段的所有不同值(例如,國家字段“co” - 但我會有其他字段)我不在乎給定值出現了多少次或誰/什么它與-我只需要當前在其中的不同國家/地區的列表。

我有這個可以生成列表 - 但由於明顯的原因,它的速度慢得令人無法接受,因為它正在查詢 AD 中的每條記錄並在發現新國家/地區時將它們添加到列表中。

Public Function GetAllCountries() As List(Of String)

    Dim searcher As DirectorySearcher = ActiveDirectory.Forest.GetCurrentForest.FindGlobalCatalog.GetDirectorySearcher
    Dim searchResults As SearchResultCollection
    Dim properties As ResultPropertyCollection
    Dim countryList As New List(Of String)
    Dim country As String

    Try
        With searcher
            .Filter = "(&(objectClass=user)(co=*))"
            .PageSize = 1000
            .SizeLimit = 0
            .SearchScope = SearchScope.Subtree
            .CacheResults = False
            .PropertiesToLoad.Add("co")
            searchResults = .FindAll
        End With

        For Each result As SearchResult In searchResults
            properties = result.Properties
            country = GetPropertyValue(properties("co")).SingleItem
            If Not countryList.Contains(country) Then countryList.Add(country)
        Next

    Catch ex As Exception

    End Try

    Return countryList

End Function

僅供參考GetPropertyValue只是一個自定義 function 我放在一起從Property object 中提取字符串值...

有什么方法可以使用DirectoryServices (或合適的替代方法?)以更有效的方式查詢特定 AD 字段的不同值?

不幸的是,在 LDAP 中沒有等效於 SQL 的DISTINCT 而且我看到您已經在盡最大努力使搜索盡可能快(僅要求在co屬性中具有值的帳戶,並使用PropertiesToLoad以便僅返回一個屬性)。

我認為您可以做出的唯一改進是使用HashSet而不是List 它一遍又一遍地使用List.Contains()保存,這是一個O(n) operation ,而它是O(1) with HashSet 如果列表永遠不會變得那么大,改進可能不會很明顯,但值得一試,特別是如果此代碼需要運行多次。

例如:

Dim countryList As New HashSet(Of String)(1000)

然后:

For Each result As SearchResult In searchResults
    properties = result.Properties
    country = GetPropertyValue(properties("co")).SingleItem
    countryList.Add(country)
Next

請注意,我在聲明HashSet時設置了它的大小。 這使它免於在添加元素時調整大小

您也不需要檢查它是否已經在HashSet中,因為如果它已經存在Add()就不會添加它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM