13

Every example of SOQL queries being used (the official documentation, for example) shows a new map being populated with the results of an SOQL query like this -

Map<ID, Account> m = new Map<ID, Account>([SELECT Id, Name FROM Account LIMIT 10])

I'd like to populate a map that's been created outside of one method in my class, so that I can retrieve values from it in another method.

But when I try

Map<Id,ProjectxOpp__c> pxOs = [SELECT Id,Opportunity__r.Account.Name
                                 FROM ProjectxOpp__c
                                WHERE Opportunity__c IN :stage4EuOpps.keySet()];

I get an error

Illegal assignment from List to Map

I know that I could create a map in my method with the results of the query & then copy that map to the map outside my method but this seems like a waste of time.

Is it possible to populate an existing map from an SOQL query?

  • The example from the documentation is correct as well, but you need to use all of it Map<Id,ProjectxOpp__c> pxOS = new Map<Id,ProjectxOpp__c>([SELECT...]); – Fernando Gavinho Mar 22 '17 at 9:08
  • @FernandoGavinho thanks but it looks like you might have misread my question. I was looking for a way to avoid creating a new map to store the results of my query. – Alex S Mar 22 '17 at 9:15
  • Oh, true. Sorry =/ – Fernando Gavinho Mar 22 '17 at 10:19
13

Try this, from the doc they say that putAll can take an sObjectArray (list of sObjects)

pxOs.putAll([SELECT Id,Opportunity__r.Account.Name
                                 FROM ProjectxOpp__c
                                WHERE Opportunity__c IN :stage4EuOpps.keySet()]);
  • 1
    Thanks! That's compiled. I'll accept this answer as soon as the 7 minutes is up. – Alex S Mar 17 '17 at 14:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.