4

Is it possible to group by a common field value? There is no aggregate integer, just simply a shared value in a custom field.

For example:

SELECT Franchise_Account__c, Id, 
FROM Account 
WHERE Franchise_Account__c IN (:franchise_accounts)
AND RecordType.Name = 'Customers'

In this result each Customer belongs to a Franchise_Account__c, so I would like them grouped by that.

Essentially I would like to have a Map object to index them by, something like

Map<Id,List<Account>> => Map<Franchise_Account__c,List<Custom Accounts>>

Any thoughts on how to make this happen would be AWESOME!

1 Answer 1

6

We wrote a tool to do this called GroupBy. Unfortunately I can't share it with you, but the gist is pretty straightforward. I highly recommend adding such a tool to your library as well. The tricky part is you need a method for each type of field you can group by, and you may also want to support Schema.SObjectField as your field type.

An example:

global static Map<Date, List<sObject>> dates( String field, List<sObject> records )
{
    Map<Date, List<sObject>> returnMap = new Map<Date, List<sObject>>();
    for ( sObject record : records )
    {
        Date key = (Date)record.get( field );
        if (!returnMap.containsKey( key ))
            returnMap.put( key, new List<sObject> ());
        returnMap.get( key ).add( record );
    }
    return returnMap;
}

After templating that out for all the types you want to support, your usage would look like:

Map<Id,List<Account>> franchiseToAccounts = GroupBy.ids('Franchise_Account__c', [
    SELECT Franchise_Account__c
    FROM Account 
    WHERE Franchise_Account__c IN (:franchise_accounts)
    AND RecordType.Name = 'Customers'
]);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .