0

I want to avoid this For loop inside another For... Is there any way for my situation?


  public class ManagerAccountTeamMember {
  public static Boolean isFirstTimeBEFORE = true;

  public static void myMethod (List TeamMembers) {

    for( AccountTeamMember accTeamMember: TeamMembers){
        if(accTeamMember.TeamMemberRole == '001'){
           isFirstTimeBEFORE = false;
           accTeamMember.Code__c = '001';
         } 

         if(isFirstTimeBEFORE) {
            isFirstTimeBEFORE = false;

            Map accId_X_TeamMember = new Map();

             for(AccountTeamMember TeamMember : TeamMembers) {
                     accId_X_TeamMember.put(TeamMember.AccountId,TeamMember);
             }
    
             List accounts = [SELECT Id,RecordTypeId,OwnerId FROM Account WHERE Id IN: accId_X_TeamMember.keySet()];

             for(Account account : accounts) {
                 if(acc.OwnerId != UserInfo.getUserId()) {
                    accId_X_TeamMember.get(account.Id).addError('Msg');
                  }
              }
        }
   }
 }    
}

     
1
  • 3
    Your outer loop could be totally removed save the static isFirstTimeBEFORE logic, whose intention is unclear. What exactly is this code supposed to do? Please edit to clarify. – David Reed Feb 7 at 5:20
0

P.s: The correct is Set<String> accId = new Set<String>();
and Map<String,AccountTeamMember> accId_X_TeamMember = new Map<String,AccountTeamMember>();

What I did:

  1. I created a Set to add the AccountIds of AccountTeamMembers
  2. So I use the method contais to search the itens of the Set in the another for looping

public class ManagerAccountTeamMember {
   public static Boolean isFirstTimeBEFORE = true;

   public static void myMethod (List TeamMembers) {
      if(isFirstTimeBEFORE) {
         isFirstTimeBEFORE = false;

         SetString>  accId = new SetString>();
         Map accId_X_TeamMember = new Map();

         for(AccountTeamMember TeamMember : TeamMembers) {
            if(accTeamMember.TeamMemberRole == '001'){
               accTeamMember.Code__c = '001';
                  accId.add(TeamMember.AccountId);  
             }
             accId_X_TeamMember.put(TeamMember.AccountId,TeamMember);
         }
    
         List accounts = [SELECT Id,RecordTypeId,OwnerId FROM Account WHERE Id IN: accId_X_TeamMember.keySet()];

         for(Account account : accounts) {
            if(!accId.contains(account.Id)){
               if(acc.OwnerId != UserInfo.getUserId()) {
                  accId_X_TeamMember.get(account.Id).addError('Msg');
               }
            }
         }
      }
   }    
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.