[SalesForce] how to remove members of a list from a set

I have a Set made up of group members – but it includes members who are managers of group members.

I thought I could iterate over the set and for each member of the group query the user object manager field to see if it exists:

for (id thisId: result)    {
   string MgrId= [SELECT Id FROM User WHERE ManagerId =: result].Id; 

   if (MgrId=thisId){

      } 
}

But I will probably blow the governor SOQL limits doing it this way?

So what is the correct way to remove all the elements from my list results if they are the manager of another member?

Best Answer

I just used the below code and able to remove the users who are managers to other users.

Set<Id> setUserId = new Set<Id>();
Set<Id> setManagerId = new Set<Id>();
for(User u : [select id from User]){
    setUserId.add(u.Id);
}
for(User u : [select id, ManagerId from User where ManagerId =: setUserId]){
    setManagerId.add(u.ManagerId);
}
system.debug(setUserId);
system.debug(setManagerId);
setUserId.removeAll(setManagerId);
system.debug(setUserId);

Here is the debug log

enter image description here

I have one system admin user, one standard user whose manager is the system admin users and a chatter user in my developer org.

Hope it helps.

Related Topic