Search code examples
c#linqactive-directoryprincipalcontext

using linq on active directories underlying object


Currently my code is:

using (var context = new PrincipalContext(ContextType.Domain, adDomain))
{
    using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
    {
        foreach (Principal result in searcher.FindAll())
        {
            DirectoryEntry entry = result.GetUnderlyingObject() as DirectoryEntry;
            if (entry.Properties["Company"].Value?.ToString() == "My Company")
            {
                // do some stuff
            }
        }
    }
}

I was just wondering if it would be possible to do a LINQ statement instead of the if statement to only get entries I am interested in.

Something like this:

foreach (var entry in searcher.FindAll()
    .Where(x => x.GetUnderlyingObject<DirectoryEntries>()
    .Properties["Company"].Value?.ToString() == "MY Company"))
{
    // do some stuff
}

Solution

  • It should be possible. You can use Select() first to cast the object to the DirectoryEntry's. Something like this should work:

    var entry = searcher.FindAll()
        .Select(x => (DirectoryEntry)x.GetUnderlyingObject())
        .Where(x => x.Properties["Company"].Value?.ToString() == "My Company")
        .FirstOrDefault();  // or .ToList() depending on your requirements
    
    if (entry != null)
    {
        // do some stuff
    }