6

How can i check if a user (not the current user) exists in a group. The SPGroup object allows to check if the current user is member of the group, but there is no method that checks if a SPUser given in parameter exists or not.

Someone has any idea ?

5 Answers 5

9

I use an extension method, like this:

    public static bool InGroup(this SPUser User, string GroupName)
    {
        return User.Groups.Cast<SPGroup>().Any(g => g.Name.ToLower() == GroupName.ToLower());
    }

Then call it like this:

bool inGroup = spuser.InGroup("GroupName");
4

I think you have to look at the SPUser instead of the SPGroup: SPUser has a Groups collection you can iterate and look for the group name.

Something like:

foreach ( SPGroup group in user.Groups )
    if ( group.Name == groupName )
        // found it
3
  • 1
    In terms of scalability this is a better solution as you could have groups with potentially large numbers of users, but a user is unlikely to be a member of so many groups. Its a minor point, but everything helps right? Commented Mar 10, 2010 at 9:37
  • Thats a pretty good point Charles. I posted my answer before I saw Anders. Maybe the decision will also include whether you already have an SPGroup/SPUser to iterate? Commented Mar 10, 2010 at 9:40
  • You can find some nifty helper methods for this in SPExLib: spexlib.codeplex.com/SourceControl/changeset/view/22718#339608 Commented Mar 10, 2010 at 11:46
3

you could try SPGroup.ContainsCurrentUser, after having opened your SPSite with the SPUserToken of your target user.

3
  • ContainsCurrentUser is good only when you want to check the current logged in user. This will not help Alex. He will have to check the SPUser.Gropus collection. Commented Aug 30, 2011 at 13:35
  • 2
    I suggested to open the SPSite with the SPUserToken of the target user. This should set the "Current User" context to the target user. Commented Sep 1, 2011 at 13:49
  • You are my hero.
    – boflynn
    Commented Jun 27, 2012 at 14:48
0

The SPGroup has a Users property which is a SPUser collection. Why not just loop through that and look for the SPUser that way?

1
  • This will have performance issues, since a group can contain many number of users, This will result in looping many times to check one user. consider using SPUser.Group collection instead. Commented Aug 30, 2011 at 13:36
0

For a client-side JavaScript solution, this article describes how to determine if a not-current-user is a member of a group. http://chrissyblanco.blogspot.com/2007/07/determining-whether-user-is-member-of.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.