2017-06-16 1 views
1

私はユニークな、または別個の部門名をADから取得したいので、そのための正しいクエリは何ですか。私のコードは以下の通りです:Asp .NetのActive Directoryから別の部門名を取得するにはどうすればいいですか?

private static DomainController GetDomainController(string domainpath) 
{ 
    var domainContext = new DirectoryContext(DirectoryContextType.Domain, domainpath); 
    var domain = Domain.GetDomain(domainContext); 
    var controller = domain.FindDomainController(); 
    return controller; 
} 

private static MyMethod() 
{ 
    var domainController = GetDomainController(ActiveDirectorySettings.DomainPath); 

    // Lookup the information in AD 
    var ldapEntry = new DirectoryEntry(string.Format("LDAP://{0}", domainController)) { AuthenticationType = AuthenticationTypes.Secure | AuthenticationTypes.FastBind }; 
    DirectorySearcher ds; 

    ds = new DirectorySearcher(ldapEntry) 
    { 
     SearchScope = SearchScope.Subtree, 
     Filter = "(&" + "(objectClass=user)" + "(department=" + departmentname + "*))" 
    }; 

    ds.PropertiesToLoad.Add("department"); 
    if (ds.FindAll().Count >= 1) 
    { 
     //do something.... 
    } 
} 

ここでは、重複を含むすべての部門名を取得しています。しかし、私が欲しいのは -

3人のユーザーが同じ部門(X)に所属している場合、3回は1回は部門(X)を望みます。

+0

あなたは 'GetDomainController'関数の定義を提供してください。現在、あなたの投稿には欠落しています。 – RBT

+0

'ActiveDirectorySettings.DomainPath'を使用するには、dllまたは名前空間が必要ですか?あなたのコードをコンパイルできません。 – RBT

+0

'(ActiveDirectoryConfiguration)ConfigurationManager.GetSection(" ldapConfiguration ")' –

答えて

3

LINQを使用すると、一意の検索結果を得ることができます。あなたは、このコードを書き、あなたのC#ファイルでusing System.Linq;名前空間を含める必要があります

if (ds.FindAll().Count >= 1) 
{ 
    var overallSearchResult = ds.FindAll(); 
    //to apply distinct on path property of elements in the collection 
    var uniqueSearchResultsForPath = overallSearchResult.Cast<System.DirectoryServices.SearchResult>().Select(x => x.Path).Distinct(); 

    //To apply distinct on any specific property in the "Properties" property of the elements in the collection 
    //this will give you list of distinct departments for example 

    var uniqueSearchResultsForDepartment = overallSearchResult.Cast<System.DirectoryServices.SearchResult>().Select(x => x.Properties["department"][0]).Distinct(); 
} 

:ここにコードスニペットです。

+0

まだ結果が重複しています –

+0

どのプロパティで別の結果が必要ですか?コレクション内のオブジェクトにプロパティをフェッチし、それにdistinctを適用することができます。コードを更新しました。それは 'path'プロパティの別個の値を与えます。 – RBT

+0

LINQクエリの 'Select'句に適用できるいくつかのサンプル述語を追加して、コレクション内のオブジェクトの特定のプロパティに識別性を適用しました。 – RBT

関連する問題