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
AchtungAchtung 

How to avoid nested For Loops?

I am trying to reduce the inefficiency of my code by avoiding nested For Loops. Any advice on you can give based from my code below?

I'm basically updating all the related Job Addresses of a Contact if the Contact's Other Address is updated.
Trigger ChangeJobAddress on Contact (before update) {
           
        Set<Id> setOfContacts = new Set<Id>();
        for(Contact c : Trigger.new){
            
            if(c.Other_Address__c != Trigger.oldMap.get(c.Id).Other_Address__c)
                setOfContacts.add(c.Id);           
        }
                
        if(setOfContacts.size() > 0){            
            Map<Id, List<sked__Job__c>> ContactJobs = new Map<Id, List<sked__Job__c>>();
            List<sked__Job__c> jobsAddress = new List <sked__Job__c>();
            
            jobsAddress = [SELECT Id, JobName, JobType__c, 
                           JobAddress__c,StartDate__c, ContactName__c,
                           JobLocation__c, JobStatus__c
                           FROM Job__c
                           WHERE JobType__c = 'Non-Recurring'
                           AND JobStart__c > TODAY
                           AND JobLocation__c = NULL
                           AND (JobStatus__c != 'Complete')
                           AND ContactName__c IN :setOfContacts
                           ORDER BY Name];
                      
            for (Job__c job : jobsAddress){
                if (ContactJobs.get(job.ContactName__c) == NULL){
                    ContactJobs.put(job.ContactName__c, new List<sked__Job__c>());                  
                }
                ContactJobs.get(job.ContactName__c).add(job);
            }               
            
            for(Contact con : Trigger.new){                
                if (ContactJobs.size() > 0){                             
                    if (ContactJobs.get(con.Id).size() > 0){   
                        //NEED TO AVOID THIS ONE
                        for (Job__c j :ContactJobs.get(con.Id)){
                            string otherStreet = Trigger.oldMap.get(con.Id).OtherStreet;
                            string otherCity = Trigger.oldMap.get(con.Id).OtherCity;
                            string otherState = Trigger.oldMap.get(con.Id).OtherState;
                            string OtherPostal = Trigger.oldMap.get(con.Id).OtherPostalCode;
                            string addressFormat1 = otherStreet + ', ' + otherCity + ', ' + otherState + ' ' + otherPostal;
                            string addressformat2 = otherStreet + ', ' + otherCity + ' ' + otherState + ' ' + otherPostal;
                            
                            if(j.JobAddress__c == addressFormat1 || j.JobAddress__c == addressFormat2){
                                j.JobAddress__c = con.Other_Address__c;  
                                update j;                               
                            }                            
                            else { 
                                System.debug('No Job Address updated.');     
                            }
                        }
                    }
                }
            }         
        }

 
AshishkAshishk
Change your code to after update and try below
Trigger ChangeJobAddress on Contact (after update) {
           
        Set<Id> setOfContacts = new Set<Id>();
        for(Contact c : Trigger.new){
            
            if(c.Other_Address__c != Trigger.oldMap.get(c.Id).Other_Address__c)
                setOfContacts.add(c.Id);           
        }
                
        if(setOfContacts.size() > 0){            
           
            List<sked__Job__c> jobsAddressToUpdate = new List <sked__Job__c>();

			List<Contact> lstContacts=[Select id, address fields, (SELECT Id, JobName, JobType__c, 
                           JobAddress__c,StartDate__c, ContactName__c,
                           JobLocation__c, JobStatus__c
                           FROM sked__Job__r
                           WHERE JobType__c = 'Non-Recurring'
                           AND JobStart__c > TODAY
                           AND JobLocation__c = NULL
                           AND (JobStatus__c != 'Complete')                           
                           ORDER BY Name )... from contact where id in: setOfContacts];
					 
           for(contact c:lstContacts){
			if(c.sked__Job__r.size()>0){
				for(sked__Job__c a:c.sked__Job__r){
					update address field 
					and add
					jobsAddressToUpdate.add(a);
				}
			}
		   
		   }
		   
		   
			if(!jobsAddressToUpdate.isEmpty()){
				update jobsAddressToUpdate;
			}
		   
        }
		
		
}

.
AshishkAshishk
Is this working? If yes please close this.

Thanks,
Ashish
AchtungAchtung
Hi Ashish,

Seems like a logical approach, however, I need to compare the job adress to bothe the addressFormat1 or addressFormat2. 

Where can I insert these lines of code?
AchtungAchtung
Also, there is an error with the relationship declaration:

"Didn't understand relationship 'sked__Job__r' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names."