0

I have the following method which searches for users in AD:

private void SearchUsers(string firstName, string lastName)
{
    using (var context = new PrincipalContext(ContextType.Domain, request.DomainName))
    {
        var up = new UserPrincipal(context);
        var ps = new PrincipalSearcher(up);
        var userSearchResults = ps.FindAll().ToList();

        if (!string.IsNullOrEmpty(firstName))
            userSearchResults = userSearchResults.Where(
                x => x.GivenName?.ToUpper() == firstName.ToUpper()).ToList();

        if (!string.IsNullOrEmpty(lastName))
            userSearchResults = userSearchResults.Where(
                x => x.Surname?.ToUpper() == lastName.ToUpper()).ToList();                              
    }
}

Is there a more efficient way to search as opposed to the way in which the search is being done in this method? Could I use AsQueryable here?

user9393635
  • 1,369
  • 4
  • 13
  • 32
  • 2
    You use `AsQueryable()` in unit tests to moq a DB. You aren't writing a unit test --> you don't use `AsQueryable()`. – xanatos Jun 20 '18 at 20:31
  • @xanatos I was working with an nhibernate expert several years ago who showed me how to improve performance in nhibernate queries signifcantly using AsQueryable(). So AsQueryable() is not just for unit tests – user9393635 Jun 20 '18 at 20:33
  • @xanatos all of the classes you just mentioned are native to c# api – user9393635 Jun 20 '18 at 20:34
  • 2
    Can't say for sure with the information you've provided, but I'd guess that the nhibernate expert was using AsQueryable() to build a dynamic database query based on conditions (similar to what you've shown). The benefit being that the sql doesn't get generated until later on. In this case, it looks like you're hitting something like Active Directory. Calling the FindAll() method pulls all the records into memory, so AsQueryable() will do nothing for you. You should look into using a QueryFilter. – Matt M Jun 20 '18 at 20:59
  • @xanatos [There are some use cases for AsQueryable besides just unit tests](https://stackoverflow.com/a/20379242/1159478). Granted, they're pretty fringe cases. I think I've seen one person do option #2, which I'm not even sure is a good idea, and #3 is pretty rare. Mocking something is by far the most common use case. – Servy Jun 20 '18 at 21:24

0 Answers0