function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ExploreForceExploreForce 

Remove User from multiple group

Based on the picklist value selected for user, GrpMem should retain only that user and corresponding group.
And remove the other groups associated with that user.
Any idea to improve this?

global without sharing class UsrGrpClass {

  public void UsergroupMethod(List<User> usr)
  {
    list<String> listGroups = new list<String>();
    Map<String,Group> mapGrp = new Map<String,Group>();
    Schema.DescribeFieldResult fieldResult =  User.User_Group__c.getDescribe();
    List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
  
    for(Schema.PicklistEntry f : ple){
      listGroups.add(f.getlabel());
    }
    
    List<String> sGroupIds = new List<String>();
    list<Group> listGrp = [Select Id,DeveloperName,Name From Group where Type = 'Regular' And Name = :listGroups];
    system.debug(listGrp);
    for(Group g:listGrp)
    {
       sGroupIds.add(g.id);
    }
  
    //Get all group names and users based on the groupids in picklist
    Set<Id> userId = new Set<Id>();
    List<GroupMember> delGroupIds = new List<GroupMember>();
    map<string, list<Id>> groupNameUserMapping = new map<string, list<Id>>();
    List<GroupMember> listGrpm = [SELECT Id, group.name,userorGroupId  FROM GroupMember where userorGroupId IN:sGroupIds];
                                   //where (UserOrGroupId IN :sGroupIds AND group.type='Regular')];
    system.debug(listGrpm);

    //Get all the group names and Users based on User record
    List<user> userRecord = (List<user>)ousr;
    List<GroupMember> listgroup = [Select Id,group.name,userorGroupId from GroupMember where userorGroupId IN:userRecord];
    system.debug(listgroup);
    List<String> sGroupMemIds = new List<String>();
    List<String> sGroupNames = new List<String>();
    //Set<Id> sGroupMemIds = new Set<Id>();
    for(GroupMember gpm :listgroup)
    {
        sGroupMemIds.add(gpm.userorGroupId);
        sGroupNames.add(gpm.group.name);
    }
  
  
 
    //Traverse through the groupmembers
    for(GroupMember gm:listGrpm)
    {
  
        if(sGroupMemIds.equals(gm.userorGroupId) && sGroupNames.equals(gm.group.name))
        {
               //Retain user
       }
        else
        {
               delGroupIds.add(gm);
        
        }
         userId.add(gm.userOrGroupId);
    }

    If(delGroupIds.size() > 0)
            delete delGroupIds;

}

}
pconpcon
The following code should do what you want.  I condensed down the logic significantly.  This will remove any GroupMember for any user in the list that does not have the same name as the value in User_Group__c.  It is important to note that the way I did this means that it is case sensitive.  If you need it to not be, you'll need to modify the conditional to use String.equalsIgnoreCase method.

global without sharing UsrGrpClass {
	public void UsergroupMethod(List<User> usr) {
		Map<Id, User> userMap = new Map<Id, User>(usr);
		List<String> groupList = new List<String>();

		for (Schema.PicklistEntry ple: User.User_Group__c.getDescribe().getPicklistValues()) {
			groupList.add(ple.getLabel());
		}

		Map<Id, Group> groupMap = new Map<Id, Group>([
			select DeveloperName,
				Name
			from Group
			where Type = 'Regular' and
				Name in :groupList
		]);

		Set<Id> idSet = new Set<Id>();
		idSet.addAll(groupMap.keySet());
		idSet.addAll(userMap.keySet());

		List<GroupMember> membersToDelete = new List<GroupMember>();

		for (GroupMember groupMember: [
			select Group.Name,
				UserOrGroupId
			from GroupMember
			where UserOrGroupId in :idSet or
				GroupId in :idSet
		]) {
			User user = userMap.get(groupMember.UserOrGroupId);

			if (user == null) {
				continue;
			}

			if (user.User_Group__c != groupMember.Group.Name) {
				membersToDelete.add(groupMember);
			}
		}

		if (membersToDelete.isEmpty()) {
			return;
		}

		delete membersToDelete;
	}
}

Note: This code has not be tested.  It may contain typographical or logical errors.