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
Priyesh Misquith 12Priyesh Misquith 12 

combining the similar line item from the list of values.

I have the list of line item from Opportuntiy
List<products__c> allProducts = [select id, name, quantity__c, price__c ,totalPrice__c from products  where id:= parentOppIdid];

In the above list i am having  multiple  product with same name and  
i want to combine the similar product as one ie combinig the similar product and adding the quantity__c ,totalPrice__c for productlineitem.

suppose list has
name=apple, quantity__c=2 , price__c= 20 , totalPrice__c = 40
name = watermelon , quantity__c=1 , price__c = 10 , totalPrice__c = 10
name = apple , quantity__c=3 , price__c = 20 , totalPrice__c = 60

I need a single list like

name = apple , quantity__c = 5 , price__c = 20 ,totalPrice__c = 100
name = watermelon , quantity__c=1 , price__c = 10 , totalPrice__c = 10

 
Agustin BAgustin B
Hi Priyesh, you could use a map using the name as the key.
Something like this:
List<products__c> allProducts = [select id, name, quantity__c, price__c ,totalPrice__c from products  where id:= parentOppIdid];
map<String,Products__c> productsByNameMap = new map<String,Products__c>();
for(Products__c p : products__c){
if(productsByNameMap.get(p.name)!=NULL){
productsByNameMap.get(p.name).Quantity_c = productsByNameMap.get(p.name).Quantity_c + p.quantity;
productsByNameMap.get(p.name).TotalPrice__c= productsByNameMap.get(p.name).TotalPrice__c+ p.TotalPrice__c;
}else{
productsByNameMap.put(p.name,p); 
}
}

productsByNameMap.values() is the list with what you need, if the code has no errors.

if it helps please like and mark as correct as it may help others.
Agustin BAgustin B
sorry,try this one please:
List<products__c> allProducts = [select id, name, quantity__c, price__c ,totalPrice__c from products  where id:= parentOppIdid];
map<String,Products__c> productsByNameMap = new map<String,Products__c>();
for(Products__c p : products__c){
if(productsByNameMap.get(p.name)!=NULL){
Products__c prodMap = productsByNameMap.get(p.name);
prodMap.Quantity_c = prodMap.Quantity_c + p.Quantity_c;
prodMap.TotalPrice__c= prodMap.TotalPrice__c+ p.TotalPrice__c;
productsByNameMap.put(p.name,prodMap);
}else{
productsByNameMap.put(p.name,p); 
}
}

 
Priyesh Misquith 12Priyesh Misquith 12
Hi Agustin B,

I am generating one pdf on click of a button and i want show the combined order line items in pdf. I am not updating any object.

I am getting following error while trying your approach

Field is not writeable: products__c.Quantity_c
Field is not writeable: products__c.TotalPrice__c

Is there any Other approach i can try.
Priyesh Misquith 12Priyesh Misquith 12
Hi Agustin B,

Quantity_c , TotalPrice__c are formula fields in org