Naveen Kumar
Naveen Kumar

Reputation: 1432

How to get distinct departments name from Active Directory in Asp .Net?

I want to get unique or distinct departments name from AD so what is the correct query for that. Below is my code:

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....
    }
}

Here I am getting all the departments name including duplicates. But what I want is -

If 3 users belongs to the same department(X) then I want department(X) once not thrice.

Upvotes: 1

Views: 1380

Answers (1)

RBT
RBT

Reputation: 25877

You can use LINQ to get unique/distinct search results. Here is the code snippet:

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();
}

You will have to include using System.Linq; namespace in your C# file where you write this code.

Upvotes: 3

Related Questions