Search code examples
c#foreachactive-directorydirectoryentrygroupprincipal

Check if a DirectoryEntry is the last of a Group in Active Directory C#


Hello, I need to check if a DirectoryEntry is the last one of a Group in AD. I don't know why, but my boss says he want a Messagebox. The method below is just a little part of my big project. What it does? I gets all users of a group in AD. Every user is saved in a DirectoryEntry. Then I am calling some other stuff. This is irrelevant for this Question see "Do Stuff if de".

I don't know how to get the last element thats why I put this:

var lastelement = users.LastElement;

in the method.

    private void Abgleich()
    {
        log.Debug("Abgleich in ActivDirectory aufgerufen");
        using (var context = new PrincipalContext(ContextType.Domain, Properties.Settings.Default.Servername, Properties.Settings.Default.Container))
        {
            using (var group = GroupPrincipal.FindByIdentity(context, Properties.Settings.Default.ECADGruppe))
            {
                if (group == null)
                {
                    log.Error("Group does not exist");
                }
                else
                {
                    var users = group.GetMembers(true);

                    //Pseudo Code
                    var lastelement = users.LastElement;
                    //End Pseudo Code

                    foreach (UserPrincipal user in users)
                    {
                        DirectoryEntry de = (user.GetUnderlyingObject() as DirectoryEntry);
                        // Do Stuff if de
                        if (de == lastelement)
                        {
                            XtraMessageBox.Show("This is the last", "Remember", MessageBoxButtons.YesNo, MessageBoxIcon.Info);
                        }
                    }
                }
            }
        }
    }

Solution

  • There are several ways to find the last object in a collection.

    Note: Intellisense won't show all methods if you use var instead of classname in declarations.

    One way is to store the last object of the collection in a variable

      PrincipalSearchResult<Principal> users = group.GetMembers(true);
    
    
      UserPrincipal lastuser = (UserPrincipal)users.Last();
    
    
      foreach (UserPrincipal user in users)
      {
        //...
    
        if (user == lastuser)
        {
          // Messagebox
        }
      }
    

    Other option is to use a iterate variable

      for (int i = 0; i < users.Count(); i++)
      {       
    
        if (i == users.Count())
        {
          // .. last user
        }
    
      }