Scenario
A New Lead is inserted, if it matches criteria, the lead ownerid is Updated based on an email field on the lead.
Problem
Write code that takes the email address and queries all Users for one which has an email matching the lead field.
Question
How do I optimize this Operation? I currently am doing it with 3 nested for loop. I would like to do this using a map< email,User> so I can take advantage of the loopups instead of raw iteration. This method is inside a trigger helper class. Newlead is a a map of newleads.
Public static void updateOwnerIdForPartner() {
List<lead> leadsToUpdate = new list<lead>();
List<String> emails = new list<String>();
for(Lead lead: newLead) {
if(lead.Sales_Rep_Email__c != null && lead.recordtypeid == '012C0000000M000000' && lead.LeadSource == 'Partner') {
leadsToUpdate.add(lead);
emails.add(lead.Sales_Rep_Email__c);
}
}
if(leadsToUpdate.size() > 0) {
for(List<user> users: [SELECT Id, email FROM user WHERE email IN :emails]) {
for(User user : Users) {
for(Lead lead : leadsToUpdate) {
if(lead.Sales_Rep_Email__c == user.email) {
lead.OwnerId = user.id;
}
}
}
}
}
}
newLeads
orleadsToUpdate
? You should avoid usingstatic
properties to track stateful data.