You need to sign in to do that
Don't have an account?

How can I use Map instead of inner for loop?
I wrote a trigger to count number of open cases for contacts.
To reduce complexity and obey governor limits, how can I use Map instead of inner for loop in this case?
To reduce complexity and obey governor limits, how can I use Map instead of inner for loop in this case?
trigger CountOpenCases on case (after insert, after update) { List<Case> caseList = trigger.new; set<Id> contactIdSet = new set<Id>(); for(Case cs: caseList ){ contactIdSet .add(cs.contactId); } if(contactIdSet.size() > 0){ List<contact> lstcontact = [select id, (select id, status from Cases)from contact where id IN: contactIdSet ]; if(lstcontact.size() > 0){ for(contact acc: lstcontact) { Integer openCases = 0; for(Case c : acc.cases){ if(c.Status != 'Closed') openCases++; } acc.Open_Cases__c = openCases; } update lstcontact; } } }
You can use the below changes to remove the inner for loop without Map:
trigger CountOpenCases on case (after insert, after update) {
List<Case> caseList = trigger.new;
set<Id> contactIdSet = new set<Id>();
for(Case cs: caseList ){
contactIdSet .add(cs.contactId);
}
if(contactIdSet.size() > 0){
List<contact> lstcontact = [select id, (select id, status from Cases where status!= 'Closed')from contact where id IN: contactIdSet ];
if(lstcontact.size() > 0){
for(contact acc: lstcontact)
{
acc.Open_Cases__c = acc.cases.size();
}
update lstcontact;
}
}
}
Thanks,
Maharajan.C