Hi @BeUnique , Welcome to Microsoft Q&A,
To get the number of Active Directory users from C# without using a foreach loop, you can use the PrincipalSearcher class in the System.DirectoryServices.AccountManagement namespace. This allows you to perform a simple query to get the number of users. Below is a sample code in C# to get the number of Active Directory users without using a foreach loop, you can use the PrincipalSearcher class in the System.DirectoryServices.AccountManagement namespace. This allows you to perform a simple query to get the number of users. The following is a sample code
using System;
using System.DirectoryServices.AccountManagement;
using System.Linq;
namespace xxx
{
internal class Program
{
static void Main(string[] args)
{
int userCount = GetActiveDirectoryUserCount();
Console.WriteLine("Active Directory counts: " + userCount);
Console.ReadLine();
}
static int GetActiveDirectoryUserCount()
{
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
UserPrincipal userPrincipal = new UserPrincipal(context);
PrincipalSearcher searcher = new PrincipalSearcher(userPrincipal);
var results = searcher.FindAll();
return results.Count();
}
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.