title: Get list of user in Active Directory
body: <p>I am writing an application that needs to get a list of users from a specified domain. I can get the users now, but it is way to slow how can I do this faster especially on larger domains?</p>
  
  <pre><code>using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain))
          {
              UserPrincipal userPrincipal = new UserPrincipal(pc);
  
              PrincipalSearcher search = new PrincipalSearcher(userPrincipal);
  
              PrincipalSearchResult&lt;Principal&gt; results = search.FindAll();
  
              foreach (var principals in results.Partition(20))
              {
                  IDictionary&lt;string, string&gt; users = new Dictionary&lt;string, string&gt;(20);
                  foreach (UserPrincipal principal in principals.Cast&lt;UserPrincipal&gt;())
                  {
                      users.Add(principal.SamAccountName, principal.DisplayName);
                  }
  
                  yield return users;
              }
          }
  </code></pre>
  
  <p>Basically in the outer foreach loop I am getting an IEnumerable of IEnumerable>. I did that so I could try to incrementally load a few at a time and display them to the user while the rest are still loading, but once I hit that inner loop I get a several minute hang.</p>
  
  <p>I am trying to get the users name in domain\username format as well which I haven't figured out how to do either.</p>