0
List1<account>: ({Name=Acc1, type__c=Marketing,Agree__c=no},{Name=Acc2, type__c=Sales,Agree__c=yes})
List2<account>: ({Name=Acc1, Sla__c=new},{Name=Acc2, Sla__c=pending})

I need to compare list1's name == list2's name and then concatenate/merge two lists into 1 record.

List3<account>: ({Name=Acc1, type__c=Marketing,Agree__c=no,Sla__c=new},{Name=Acc2, type__c=Sales,Agree__c=yes,Sla__c=pending})

Please let me know if it is possible.

1
  • 1
    Yes, it is possible. The "merging" aspect is pretty manual, but SObject's .get() and .put() methods are helpful. What have you tried? Where are you stuck?
    – Derek F
    Commented Jul 29, 2021 at 17:22

1 Answer 1

1

As a general rule, you can do that with a Map:

// given list1 and list2 are populated with list of records.
// ObjectType should be Account, Contact, MyCustomObject__c, whatever

Map<String, ObjectType> masterMap = new Map<String, ObjectType>();
for(ObjectType record: list1) {
  masterMap.put(record.Name, new ObjectType());
}
for(ObjectType record: list2) {
  masterMap.put(record.Name, new ObjectType());
}
for(ObjectType record: list1) {
  Map<String, Object> populatedFields = record.getPopulatedFieldsAsMap();
  sObject masterRecord = masterMap.get(record.Name);
  for(String field: populatedFields.keySet()) {
    masterRecord.put(fields, populatedFields.get(field));
  }
}
for(ObjectType record: list2) {
  Map<String, Object> populatedFields = record.getPopulatedFieldsAsMap();
  sObject masterRecord = masterMap.get(record.Name);
  for(String field: populatedFields.keySet()) {
    masterRecord.put(fields, populatedFields.get(field));
  }
}
ObjectType[] list3 = masterMap.values();

The end result is a list of records merged by name with all the values populated. Note that this example has Name as a case-sensitive value (so Demo won't match demo). If you need it to be case insensitive, you'll need to lowercase the key strings so they'll match.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .