You need to sign in to do that
Don't have an account?
Sparky Jane
How to avoid writing query in for loop?
Can someone please help me out from avoiding writing query in for loop (for(Account ac:accList)) ?
public class AccountsAndContacts{
public void acc(){
Map<Id,List<Contact>> contactslist = new Map<Id,List<Contact>>();
List<Account> accList = [SELECT name from Account];
for(Account ac:accList){
list<Contact> con=[select name from Contact where Account.Id=:ac.Id];
contactslist.put(ac.Id,con);
}
for(Account ac:accList){
System.debug('Account Name: '+ac.name);
System.debug('Contacts List: '+contactslist.get(ac.Id));
}
}
}
public class AccountsAndContacts{
public void acc(){
Map<Id,List<Contact>> contactslist = new Map<Id,List<Contact>>();
List<Account> accList = [SELECT name from Account];
for(Account ac:accList){
list<Contact> con=[select name from Contact where Account.Id=:ac.Id];
contactslist.put(ac.Id,con);
}
for(Account ac:accList){
System.debug('Account Name: '+ac.name);
System.debug('Contacts List: '+contactslist.get(ac.Id));
}
}
}
All Answers
This will mean that your accounts each have a child list of contacts, which you can then iterate without worrying putting the items into a map:
Below is modification of your code.
now the Query is outside of the for loop and will give the same results.
let us know if you have any question .
please don't Forget to Mark this as your best answer if it works fine for you
Regards,
Grazitti Team
Web: www.grazitti.com
The answer that you've given, helped me a lot. But I wanna do that code without missing "Map<id,List>". Is the following Code correct or not!!
public class AandCWithoutQuery{
public void acc(){
Map<Id,List<Contact>> contactslist = new Map<Id,List<Contact>>();
List<Account> accList = [SELECT name, (select id, name from Contacts) from Account];
for(Account ac:accList){
contactslist.put(ac.Id, ac.contacts);
System.debug('Account Name: '+ac.name);
System.debug('Contacts List: '+ac.contacts);
}
}
}