1

I am trying to get Id list like this:

Set<Id> idSet;
idSet = [SELECT Id FROM Account LIMIT 1];

But getting this:

Illegal assignment from List<Account> to Set<Id>

I need to do this to add id:

Set<Id> idSet = new Set<Id>();
List<Account> accountList = [SELECT Id FROM Account LIMIT 1];
idSet.add( accountList[0].Id);

But in the above solution, I need to create accountList object just to populate idSet.

Is there any other way to populate set of ids using SOQL query?

1 Answer 1

5

You can instead get the results into Map and get the keyset from Map to get Set<Id>

Map has a constructor which takes List<sObject> and creates a instance of Map with ID as Key and sObject as value.

Excerpt from Salesforce Map documentation.

Map<ID,sObject>(recordList)

Creates a new instance of the Map class and populates it with the passed-in list of sObject records. The keys are populated with the sObject IDs and the values are the sObjects.

So, you can use the above constructor of Map and can get a set out of it using Map's keyset() method.

Set<Id> idSet = new Map<Id,Account>([SELECT Id FROM Account LIMIT 1]).keyset();

You can also go through Salesforce documentation of Map of sObjects and refer Auto-Populating Map entries from a SOQL query.

2
  • 1
    +1, good explain. removed my answer Aug 3, 2019 at 8:23
  • 2
    @salesforce-sas Thanks for correcting the syntax Aug 3, 2019 at 8:36

You must log in to answer this question.

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