Skip to main content

 // Fetch the data from car and its child object and store in a list.

List<Car__c> carUpdateList =new List<Car__c>();         

List<Car__c> CarList =[select id, Total_Expence__c, (select id,Service_Amount__c from Car_Services__r), (select id,Accessory_Amoount__c from Car_Accessories__r) from Car__c where id IN: carIDSet];         

//Iterate through car and update the amount field on the car object.         

for(Car__c car: CarList){             

            double totalSum =0;             

            for(Car_Service__c cs: car.Car_Services__r){ 

                                            totalSum += cs.Service_Amount__c; 

                           }             

            for(Car_Accessory__c ca: car.Car_Accessories__r){

                             totalSum += ca.Accessory_Amoount__c; 

                   }             

            car.Total_Expence__c = totalSum;             

             carUpdateList.add(car);         

}             

update carUpdateList;

 

I have this code. How can I rewrite this functionality for avoiding for under for loop.

1 answer
  1. Oct 18, 2022, 11:16 PM

    Hi @Bhanu Pratap Singh ,

     

    Try this

     

    List<Car__c> carUpdateList =new List<Car__c>();

    List<AggregateResult> groupedResults1 = [select Car__c,sum(Service_Amount__c) from Car_Services__c where Car__c IN: carIDSet oederby Car__c];

    List<AggregateResult> groupedResults2 = [select Car__c,sum(Accessory_Amoount__c) from Car_Accessories__c where Car__c IN: carIDSet oederby Car__c];

    Map<Id,Integer> ServicesMap = new Map<Id,Integer>();

    Map<Id,Integer> Car_AccessoriesMap = new Map<Id,Integer>();

    for ( AggregateResult ar : groupedResults1){

    ServicesMap(ar.get('expr0'),ar.get('expr1'));

    }

    for ( AggregateResult ar : groupedResults2){

    Car_AccessoriesMap(ar.get('expr0'),ar.get('expr1'));

    }

    for(Car__c car: CarList){

    double totalSum =0;

    if (ServicesMap.get(car.Id) != null) totalSum = totalSum + ServicesMap.get(car.Id);

    if (Car_AccessoriesMap.get(car.Id) != null) totalSum = totalSum + Car_AccessoriesMap.get(car.Id);

    car.Total_Expence__c = totalSum;

    carUpdateList.add(car);

    }

    update carUpdateList;

0/9000