0

Here's the query:

Merchandise__c[] merchList = Database.query('SELECT ' + lookupFieldApiName +'.Id, '+ lookupFieldApiName +'.Name ' +
                                                                'FROM Merchandise__c ' +
                                                                'WHERE Product__c =:productId '+ merchTypeQuery + ' ' + machineConfigQuery );

What i'm trying to do is narrow this down into a list where the lookupFieldApiName.Id doesn't repeat.

The purpose is to add options to a lightning combobox on a form, the reason i need to do this is because i'm creating a dynamic combobox(picklist/selectOption) based on a hierarchy and standard picklists for a multitude of business reasons.

Also yes i've looked at other solutions but other than going wild and doing an O(n^2) algorithm, which i'd rather not, i'm not sure what i can do here.

1 Answer 1

1

Whenever you say "remove duplicates" in Apex, the first thing that should come to your mind is to use a Map.

Maps, by definition, do not have duplicate keys. If you .put() into a map, and the key already exists, the value stored for that key is overwritten.

Given you have Merchandise__c[] merchList, it's really simple.

Map<Id, Merchandise__c> uniqueLookupIdToMerch = new Map<Id, Merchandise__c>();

for(Merchandise__c merch :merchList){
    uniqueLookupIdToMerch.put(
        (Id)(
            // we first need to get and cast the related record
            ((SObject)merch.getSObject(lookupFieldApiName))
            // then further call .get() again (and cast some more)
            .get('Id')
        ), merch
    );
}

List<Merchandise__c> uniqueList = uniqueLookupIdToMerch.values();

You should also consider using the lookup field directly (which contains the related record's Id) instead of traversing the relationship to get the Id.

uniqueLookupIdToMerch.put((Id)merch.get('MyRelationshipField__c'), merch) is a lot easier on the eyes, brains, and fingers than the alternative

2
  • Seems like it should work but it gives me a fatal error "System.SObjectException: Invalid field Machine_Config__r.Id for Merchandise__c I'm guessing the issue is it's trying to traverse the relationship hierarchy.
    – ensir
    Commented May 6, 2022 at 19:26
  • @ensir my bad. For traversing the hierarchy we need to use getSObject(<relationship name>) with some typecasting, followed by .Id or .get('Id') (the latter would require more typecasting). All the more reason to just use the relationship field directly.
    – Derek F
    Commented May 6, 2022 at 19:30

You must log in to answer this question.

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