title: How do I get JUST the groups a user is in from AD without nesting
body: <p>I want to get a list of the groups a user is <strong>directly</strong> a member of (i.e. without nesting). Effectively, to retrieve what you see in the Member Of tab in AD:</p>
  
  <p><a href="https://i.stack.imgur.com/jCbtu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jCbtu.png" alt="enter image description here"></a></p>
  
  <p>I am using the following to get the list of groups:</p>
  
  <pre><code>public List&lt;GroupPrincipal&gt; GetGroups(string userName)
  {
      List&lt;GroupPrincipal&gt; result = new List&lt;GroupPrincipal&gt;();
      PrincipalContext myDomain = new PrincipalContext(ContextType.Domain, "mydomain.com");
      UserPrincipal user = UserPrincipal.FindByIdentity(myDomain, userName);
      if (user != null)
      {
          PrincipalSearchResult&lt;Principal&gt; groups = user.GetAuthorizationGroups();
          try
          {
              // iterate over all groups
              foreach (Principal p in groups)
              {
                  // make sure to add only group principals
                  if (p is GroupPrincipal)
                  {
                      result.Add((GroupPrincipal)p);
                  }
              }
          }
          catch (Exception e)
          {
  
          }
      }
      return result;
  }
  </code></pre>
  
  <p>However, this retrieves all groups including nested ones. (i.e. if there is a group in the list in the screenshot above which is nested in another group - both groups are returned).</p>
  
  <p>How can I just retrieve the list as shown in Active Directory?</p>