SPGroupCollection class

Represents a collection of SPGroup objects.

Inheritance hierarchy

System.Object
  Microsoft.SharePoint.Administration.SPAutoSerializingObject
    Microsoft.SharePoint.SPBaseCollection
      Microsoft.SharePoint.SPMemberCollection
        Microsoft.SharePoint.SPGroupCollection

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)

Syntax

'Declaration
Public Class SPGroupCollection _
    Inherits SPMemberCollection
'Usage
Dim instance As SPGroupCollection
public class SPGroupCollection : SPMemberCollection

Remarks

Use the Groups property of the SPUser class or the SPWeb class to return the collection of groups for the user or Web site. Otherwise, use the OwnedGroups property of the SPUser class to return the groups owned by a user, or the SiteGroups property of the SPWeb class to return all the groups in the site collection.

To create a group in the site collection, use the Add method.

Use an indexer to return a single group from the collection of groups. For example, assuming the collection is assigned to a variable named collGroups , use collGroups[index] in C#, or collGroups(index) in Microsoft Visual Basic, where index is either the index number of the group in the collection or the name of the group.

Examples

The following code example iterates through all the groups in a site collection and deletes all groups that are owned by the specified user.

Dim webSite As SPWeb = SPContext.Current.Site.RootWeb
Try
    Dim users As SPUserCollection = webSite.Users
    Dim user As SPUser = webSite.Users("User_Name")
 
    Dim webGroups As SPGroupCollection = webSite.SiteGroups
    Dim userGroups As SPGroupCollection = user.OwnedGroups
 
    Dim userGroup As SPGroup
    For Each userGroup In  userGroups
        webGroups.RemoveByID(userGroup.ID)
    Next userGroup
Finally
    webSite.Dispose()
End Try
using (SPWeb oWebsiteRoot = SPContext.Current.Site.RootWeb)
{
    SPUserCollection collUsers = oWebsiteRoot.Users;
    SPUser oUser = oWebsiteRoot.Users["User_Name"];

    SPGroupCollection collGroupsWebsite = oWebsiteRoot.SiteGroups;
    SPGroupCollection collGroupsUser = oUser.OwnedGroups;

    foreach (SPGroup oUserGroup in collGroupsUser)
    {
        collGroupsWebsite.RemoveByID(oUserGroup.ID);
    }
}

Note

Certain objects implement the IDisposable interface, and you must avoid retaining these objects in memory after they are no longer needed. For information about good coding practices, see Disposing Objects.

Thread safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See also

Reference

SPGroupCollection members

Microsoft.SharePoint namespace