ads

Friday 24 March 2017

Fetch All Contact Under Account Using Map Instead of Child Query

Creating a Map that Provide respected Contacts when passing Account ids


Map<Id, List<Contact>> AccountIdVslistContacts = new Map<Id, List<Contact>>();

for(Contact ConInstance: [SELECT AccountId,Id FROM Conatact]) {
 if(AccountIdVslistContacts.containsKey(ConInstance.AccountId)) {
  List<Contact> Contacts = AccountIdVslistContacts.get(conInstance.AccountId);
  Contacts.add(ConInstance.Id);
  AccountIdVslistContacts.put(ConInstance.AccountId , Contacts);
 } else {
  AccountIdVslistContacts.put(ConInstance.AccountId, new List<Contact> { ConInstance });
 }
}



Now using that map in our code to do operation on Contacts


List<Account> AccountList = new List<Account>();
 AccountList = [SELECT Id FROM ACCOUNT LIMIT 100]; 

 for(Account AccInstace:AccountList){ 
     //One by one Account will Enter in Loop
    
       //We will Pass that Account Id in Map and get those Contact ids
      for(Contact conInstance:AccountIdVslistContacts.get(AccInstance.Id)){  

            //Do your logic on Each Contact one by one
       }
 }

No comments:

Post a Comment