I have an SPGroup object populated, how can I remove all members from the group, so that essentially I start with a fresh group.
I can't delete and recreate it, so I need a way to work with the existing SharePoint group.
Thanks in advance
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It only takes a minute to sign up.
Sign up to join this communityI have an SPGroup object populated, how can I remove all members from the group, so that essentially I start with a fresh group.
I can't delete and recreate it, so I need a way to work with the existing SharePoint group.
Thanks in advance
Take a look on msdn
foreach (SPUser user in group.Users)
{
group.RemoveUser(user);
}
But be aware that you change this group for the whole site collection, if you have other site collections those won't be impacted by the modification of this group.
foreach()
call to the Users
property creates a new SPUserCollection object and gets an enumerator to that collection. The RemoveUser
call itself just gets the ID from the user object before calling its Users property (generating a new SPUserCollection) to delete the user by ID. It looks like each new SPUserCollection gets a copy of the data so you're not enumerating on the same collection you're modifying (and also creating n+1 SPUserCollection objects where n = number of users in group)
– Erik Noren
Apr 18 '18 at 17:07
while (group.Users.Count > 0)
{
group.Users.Remove(group.Users[0]);
}
This should remove all the users in the group for CSOM. Edit: It would be inefficient for SSOM, however.