C# – PrincipalSearchResult, Lambda Expressions

cienumerablelambda

I'm trying to filter out entities from a principalcollection using what I think is called lambda expressions.

I cant get this to work, I get no results.
user.GetGroups() returns all the groups where user is member, but user.GetGroups().Where(....) does not return anything.

Lets say that userprincipal user = Administrator
Lets say MyFilterString = "Exchange"
Lets say that Administrator is member of the following groups:

Exchange Domain Servers
Exchange Services
Administrators
Enterprise Admins

Domain Admins
Schema Admins


UserPrincipal user = new UserPrincipal(MyActiveDirectoryContext);
..
..
PrincipalSearchResult<Principal> memberOfGroups = user.GetGroups().Where(g => g.SamAccountName.Contains(MyFilterString) == true) as PrincipalSearchResult<Principal>;

What I expect is that memberOfGroups should now contain 2 groups:

Exchange Domain Servers
Exchange Services

But it ends up empty, zip zero, nada.
A little help is very much appreciated.

Simon O. Olsen

Best Answer

If .Where is the standard Enumerable.Where, then it isn't going to ever return a PrincipalSearchResult; so as will return null every time. Consider using .ToList() :

var memberOfGroups = user.GetGroups()
      .Where(g => g.SamAccountName.Contains(MyFilterString)).ToList()