Activity Forums Salesforce® Discussions I want to count related Contact in a Account.How can i do this in salesforce Apex Code? Reply To: I want to count related Contact in a Account.How can i do this in salesforce Apex Code?

  • Subhendu

    Member
    January 10, 2018 at 11:43 am

    Hi Suraj,

    A much-optimized code would be -

    Public static Map<Id,Integer> countRelatedContact( Set<Id> accId){

    Map<Id,Integer> relatedCountMap = new Map<Id,Integer>();
    if(!accId.isEmpty){

    for(Account acc : [select Id, name,(Select Id, Name from Contacts) from Account where Id in:accId];){

    relatedCountMap.put(acc.Id,acc.Contacts.size());
    }

    return relatedCountMap;
    }

    This will return a Map of Account Id and # of related Contacts to that Account record. Hope this helps you as per your scenario.

    Thanks,
    Subhendu