需要优化这个触发器吗?谁能帮帮我。?
Need optimization of this trigger?Can anyone help me out.?
实际上,我正在尝试将 Area_c
字段从自定义对象(邮政编码)获取到引导对象自定义字段 Area_c
。所以,我已经写了一些代码,但有没有其他方法可以编写它或对这段代码进行一些优化。
trigger OpportunityPriceBook on Lead (before insert) {
List<String> zipList = new List<String>();
for(Lead lead : Trigger.new){
zipList.add(lead.PostalCode);
}
List<Zip_Code__c> zipCodeList = [Select Id, Name, City__c, Area__c from
Zip_Code__c WHERE Name IN : zipList];
for(Lead leads : Trigger.new){
for(Integer i =0 ; i < zipCodeList.size(); i++)
{
leads.Area__c = zipCodeList.get(i).Area__c;
leads.City = zipCodeList.get(i).City__c;
break;
}
}
}
根据代码,有几种方法可以简化最后的多维 for 循环;由于它们的指数性质,嵌套的 for 循环有时会出现问题。
说到这一点,您的代码中有一个非常明显的错误:您在嵌套的 for 循环中没有标识条件语句,并且实际上每次总是只将引导符设置为第一个邮政编码的数据。
这是我会采用的方法:
// Extract out the postal codes of the leads
List<String> zipList = new List<String>();
for (Lead lead : Trigger.new) {
zipList.add(lead.PostalCode);
}
// Query for the related Zip Codes, and map them by Name
List<Zip_Code__c> zipCodeList = [SELECT Id, Name, City__c, Area__c FROM Zip_Code__c WHERE Name IN :zipList];
Map<String, Zip_Code__c> zipCodeByName = new Map<String, Zip_Code__c>();
for (Zip_Code__c zipCode : zipCodeList) {
zipCodeByName.put(zipCode.Name, zipCode);
}
// Stamp leads with the Area and City as identified by the matching Zip Code
for (Lead lead : Trigger.new) {
Zip_Code__c zipCode = zipCodeByName.get(lead.PostalCode);
lead.Area__c = zipCode.Area__c;
lead.City = zipCode.City__c;
}
实际上,我正在尝试将 Area_c
字段从自定义对象(邮政编码)获取到引导对象自定义字段 Area_c
。所以,我已经写了一些代码,但有没有其他方法可以编写它或对这段代码进行一些优化。
trigger OpportunityPriceBook on Lead (before insert) {
List<String> zipList = new List<String>();
for(Lead lead : Trigger.new){
zipList.add(lead.PostalCode);
}
List<Zip_Code__c> zipCodeList = [Select Id, Name, City__c, Area__c from
Zip_Code__c WHERE Name IN : zipList];
for(Lead leads : Trigger.new){
for(Integer i =0 ; i < zipCodeList.size(); i++)
{
leads.Area__c = zipCodeList.get(i).Area__c;
leads.City = zipCodeList.get(i).City__c;
break;
}
}
}
根据代码,有几种方法可以简化最后的多维 for 循环;由于它们的指数性质,嵌套的 for 循环有时会出现问题。
说到这一点,您的代码中有一个非常明显的错误:您在嵌套的 for 循环中没有标识条件语句,并且实际上每次总是只将引导符设置为第一个邮政编码的数据。
这是我会采用的方法:
// Extract out the postal codes of the leads
List<String> zipList = new List<String>();
for (Lead lead : Trigger.new) {
zipList.add(lead.PostalCode);
}
// Query for the related Zip Codes, and map them by Name
List<Zip_Code__c> zipCodeList = [SELECT Id, Name, City__c, Area__c FROM Zip_Code__c WHERE Name IN :zipList];
Map<String, Zip_Code__c> zipCodeByName = new Map<String, Zip_Code__c>();
for (Zip_Code__c zipCode : zipCodeList) {
zipCodeByName.put(zipCode.Name, zipCode);
}
// Stamp leads with the Area and City as identified by the matching Zip Code
for (Lead lead : Trigger.new) {
Zip_Code__c zipCode = zipCodeByName.get(lead.PostalCode);
lead.Area__c = zipCode.Area__c;
lead.City = zipCode.City__c;
}