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
Dman100Dman100 

convert List<Case> to List<Contact>

I have a List of cases and I need to convert to a list of Contacts.

 

Here is the code I have:

 

List<Case> cases = [select Case.Contact.Id from Case where Survey_ID__c > '' and Survey_Sent_Date__c = null];
System.debug('Cases = ' + cases);

 

This is the resultset returned:
Cases = (Case:{Id=500700000077OqNAAU, ContactId=0033000000J6B9YAAV}, Case:{Id=500700000077YveAAE, ContactId=0033000000J6B9YAAV}, etc...

 

How can I convert to a List of Contacts?

 

I was trying:

 

List<Case> cases = [select Case.Contact.Id from Case where Survey_ID__c > '' and Survey_Sent_Date__c = null];

List<Contact> contacts = new List<Contact>();

for (Case c : cases) { Contact con = new Contact();

contacts.add(c.contactid);

}

 

But, I get Incompatible element type Id for collection of SOBJECT:Contact

Thanks for any help.

aalbertaalbert

You are setting the Contact Id where the apex is expecting a Contact object.

 

Try this corrected code snippet:

 

List<Case> cases = [select Case.Contact.Id from Case]; List<Contact> contacts = new List<Contact>(); for (Case c : cases) {

Contact con = new Contact(id=c.contactId); contacts.add(con); }

 

 

 

JBessonartJBessonart

 

Hi, you can do it something like this:

 

 

List<id> contactsIds = new List<Id>(); for (Case c : cases) { Contact con = new Contact(); contactsIds .add(c.contactid); } List<Contact> contactList = [select id, ..... ,... from Contact where id in: contactsIds];

 

 In contactList you have the contacts that you want. If you want to copy the "data" and insert new contacts, you have to iterate on the list.

 

 

J.