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
Noam Damri 3Noam Damri 3 

How to iterate a list inside list in apex

Hey,

So i have this list:
ContactList = [select Id, Name, gender__c , phone, Account.Name, AccountId
                    (select Id,Name,subject__c,level__c                        
                     from custom_object__r)                                                    
                    from Contact];

if im iterating with a for loop on ContactList and reach to the custom_object__r fields, how will i do that?

ive tried this which is not working:
for(Contact TempCon : ContactList)
     TempCon.custom_object__r.Name = 'somthing';

ive tried to iterate the opposite way but it's not working as well:
 for(custom_object__r Temp : ContactList.custom_object__r)  
       Temp.Contact.Name = 'somthing';

Help will be appreciated

Thx!
                    
Best Answer chosen by Noam Damri 3
Vatsal KothariVatsal Kothari
Here is the code:

ContactList = [select Id, Name, gender__c , phone, Account.Name, AccountId
                    (select Id,Name,subject__c,level__c                        
                     from custom_object__r)                                                    
                    from Contact];

for(Contact con : contactList){
  
  for(custom_object__c custom : con.custom_object__r){
   custom.Name = 'Something';
  }
}
If this solves your problem, kindly mark it as the best answer.

Thanks,
Vatsal

All Answers

Ramu_SFDCRamu_SFDC
You should use maps in order to get the results of subquery something similar to the example mentioned in the below post

https://developer.salesforce.com/forums/ForumsMain?id=906F000000090bvIAA
Vatsal KothariVatsal Kothari
Here is the code:

ContactList = [select Id, Name, gender__c , phone, Account.Name, AccountId
                    (select Id,Name,subject__c,level__c                        
                     from custom_object__r)                                                    
                    from Contact];

for(Contact con : contactList){
  
  for(custom_object__c custom : con.custom_object__r){
   custom.Name = 'Something';
  }
}
If this solves your problem, kindly mark it as the best answer.

Thanks,
Vatsal

This was selected as the best answer
Noam Damri 3Noam Damri 3
Thank you Vatsal!!
it is working. and i also realized i can do this :  Con.custom_object__r[0].Name = 'somthing'; (as i know i have only one custom_object__r for each contact)

Ramu_SFDC - thank as well