title: Fast way to get a list of group members in Active Directory with C#
body: <p>In a web app, we're looking to display a list of sam accounts for users that are a member of a certain group.  Groups could have 500 or more members in many cases and we need the page to be responsive.  </p>
  
  <p>With a group of about 500 members it takes 7-8 seconds to get a list of sam accounts for all members of the group.  Are there faster ways?  I know the Active Directory Management Console does it in under a second.</p>
  
  <p>I've tried a few methods:</p>
  
  <p>1)</p>
  
  <pre><code>PrincipalContext pcRoot = new PrincipalContext(ContextType.Domain)
  GroupPrincipal grp = GroupPrincipal.FindByIdentity(pcRoot, "MyGroup");
  List&lt;string&gt; lst = grp.Members.Select(g =&gt; g.SamAccountName).ToList();
  </code></pre>
  
  <p>2)</p>
  
  <pre><code>PrincipalContext pcRoot = new PrincipalContext(ContextType.Domain)
  GroupPrincipal grp = GroupPrincipal.FindByIdentity(pcRoot, "MyGroup");
  PrincipalSearchResult&lt;Principal&gt; lstMembers = grp.GetMembers(true);
  List&lt;string&gt; lst = new List&lt;string&gt;();
  foreach (Principal member in lstMembers )
  {
      if (member.StructuralObjectClass.Equals("user"))
      {
          lst.Add(member .SamAccountName);
      }
  }
  </code></pre>
  
  <p>3)</p>
  
  <pre><code>PrincipalContext pcRoot = new PrincipalContext(ContextType.Domain)
  GroupPrincipal grp = GroupPrincipal.FindByIdentity(pcRoot, "MyGroup");
  System.DirectoryServices.DirectoryEntry de = (System.DirectoryServices.DirectoryEntry)grp.GetUnderlyingObject();
  List&lt;string&gt; lst = new List&lt;string&gt;();
  foreach (string sDN in de.Properties["member"])
  {
      System.DirectoryServices.DirectoryEntry deMember = new System.DirectoryServices.DirectoryEntry("LDAP://" + sDN);
      lst.Add(deMember.Properties["samAccountName"].Value.ToString());
  }
  </code></pre>