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
iSfdciSfdc 

Removing nested for loops

Hi,
We have a trigger written for processing in Case.
(Background: Case is linked with Accounts and an Account has many SAP Partner Role(Custom Object) )
 
Whenever a Case is Saved with an Account , it must search for SAP Partner Roles Object linked to theAccount and Update if the Account has one SAP Partner and Display an error if it has more than one SAP Partner Roles.
We are not able to eliminate the Nested for loop.Any pointers of how we can proceed to remove the Nested for loop.
 
 
Trigger SoldTo on Case(before insert,before update){
Set<Id> accountIds = new Set<Id>();
for(Case obc:Trigger.new) {
 accountIds.add(obc.AccountId);  
}
List<SAP_Partner_Roles__c> entries = new List<SAP_Partner_Roles__c>([select Id,Customer_Site__c from SAP_Partner_Roles__c where Customer_Site__c in :accountIds and SAP_Partner_Role__c='SP']);
for(Case obc:Trigger.new) {
Integer i = 0;
Id temp = null;
for(SAP_Partner_Roles__c spr: entries)
{
 if(spr.Customer_Site__c == obc.AccountId)
   { i = i + 1;
     temp = spr.Id;
   }   
}  
 if(obc.SAP_Partner_Roles__c==null)
  {
            if(i>1)
              obc.addError('There are ' +i+ ' Sold To\'s for this Account Partners, Select the right Sold To Information');
            else if(i==1)
              obc.SAP_Partner_Roles__c= temp;
  }
}
}
 
 
jlojlo
Instead of creating a List of SAP_Partner_Roles__c objects, you could create a Map of a List of SAP_Partner_Roles__c records. Your declaration would look like:

Code:
Map<Id, List<SAP_Partner_Roles__c>> partnerRolesMap = new Map<Id, List<SAP_Partner_Roles__c>>();

You would then need to populate this Map. The keys would be Customer_Site__c values and the Lists would contain all of the SAP_Partner_Roles__c records that correspond to that Customer_Site__c value. Now, when you iterate through your Cases, you can do a O(1) lookup in your Map (aka Hashtable) instead of doing an O(n) iteration through all of your SAP_Partner_Roles__c records.

If your lookup returns exactly one record in the List, do the assignment. If the lookup returns a List with multiple records, flag it with the error.