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
amyamyamyamyamyamy 

apex batch iterator query to list

Hi, I need help with my very first apex btach...

For the CustomIterable class, I am following this example:

global class CustomIterable implements Iterator<Contact>{ 
List<Contact> accs {get; set;} 
Integer i {get; set;} 
public CustomIterable(){ 
accs = [SELECT Id, Name FROM Contact WHERE Name = 'test']; 
i = 0; 
} 
global boolean hasNext(){ 
if(i >= accs.size()) 
return false; 
else
return true; 
} 
global Contact next(){ 
if(i == 8){ i++; return null;} 
i=i+1; 
return accs[i-1]; 
} 
}

 

I am trying to replace line 5 

accs = [SELECT Id, Name FROM Contact WHERE Name = 'test'];

with my codes:

List<Location_By_Zip_Code__c> zips = [select JDRF_Location__r.Name From Location_By_Zip_Code__c where Update_Zip__c= true];
for(Location_By_Zip_Code__c lbz : zips ){
List<Contact> consbyzip = [SELECT id, RecordTypeId, MailingPostalCode, AccountID, JDRF_Location__c, Do_Not_Auto_Update_Location__c, Major_Donor__c, Planned_Giving_Membership__c FROM Contact WHERE JDRF_Location__r.Name = :lbz.JDRF_Location__r.Name];
}

But I've been trying for hours, still couldn't figure out how to populate my query to a list...

 

Could anyone please help?

 

I appreciate it!! Thank you!!

Best Answer chosen by Admin (Salesforce Developers) 
Vinit_KumarVinit_Kumar

First of all,you should not be running a SOQL query inside the for loop,that is not the best practice.Please try the below code :-

 

List<String> locName = new List<String>();

List<Location_By_Zip_Code__c> zips = [select JDRF_Location__r.Name From Location_By_Zip_Code__c where Update_Zip__c= true];
for(Location_By_Zip_Code__c lbz : zips ){
locName.add(lbz.JDRF_Location__r.Name);
}

List<Contact> consbyzip = [SELECT id, RecordTypeId, MailingPostalCode, AccountID, JDRF_Location__c, Do_Not_Auto_Update_Location__c, Major_Donor__c, Planned_Giving_Membership__c FROM Contact WHERE JDRF_Location__r.Name in :locName];

All Answers

Vinit_KumarVinit_Kumar

First of all,you should not be running a SOQL query inside the for loop,that is not the best practice.Please try the below code :-

 

List<String> locName = new List<String>();

List<Location_By_Zip_Code__c> zips = [select JDRF_Location__r.Name From Location_By_Zip_Code__c where Update_Zip__c= true];
for(Location_By_Zip_Code__c lbz : zips ){
locName.add(lbz.JDRF_Location__r.Name);
}

List<Contact> consbyzip = [SELECT id, RecordTypeId, MailingPostalCode, AccountID, JDRF_Location__c, Do_Not_Auto_Update_Location__c, Major_Donor__c, Planned_Giving_Membership__c FROM Contact WHERE JDRF_Location__r.Name in :locName];

This was selected as the best answer
amyamyamyamyamyamy

It works perfectly. Thank you very much!