Is it possible to add a new list to each object in an already existing list?

List<MyObj__c> results = [SELECT Id, Name, Text__c FROM MyObj__c];

I have a second object obj2__c. I want to add this obj to each member of the list of MyObj__c. Obviously, results.add(obj2__c) won't work in this case.

How can I achieve this?

  • Is obj2__c is list of the same objects or itself a different object? – Rahul Gawale Jan 25 '19 at 2:48
  • What do you mean by "add this obj to each member of the list ..." Do you need to maintain a correspondence between a specific MyObj__c record and a specific obj2__c record? – David Cheng Jan 25 '19 at 3:33
  • 2
    Just declare results of type “List<Sobject>” and you will be able to add MyObj__c and obj2__c – javanoob Jan 25 '19 at 4:41

You just need to call addAll instead.

Adds all of the elements in the specified list to the list that calls the method. Both lists must be of the same type.

public Void addAll(List fromList)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.