Tagged: Dynamic Query, Dynamic SOQL, List, Salesforce Apex, Salesforce Customization, Salesforce Development, Salesforce sObject, Salesforce SOQL, SET, SOQL
- December 14, 2016 at 12:18 pm #17300
How can I efficiently generate a Set from a List structure in salesforce?
Hi all,
I have a bit of code where I’ve written a SOQL query that returns a list of SObject records, however I need a Set<Id> structure to pass to another method that I don’t have control of (and thus can’t change the method signature of).
How can I turn my returned List<SObject> into a Set<Id>? Is the best option just a for loop? Any guidance is appreciated.
Thanks
Tagged: Dynamic Query, Dynamic SOQL, List, Salesforce Apex, Salesforce Customization, Salesforce Development, Salesforce sObject, Salesforce SOQL, SET, SOQL
January 17, 2017 at 2:40 pm #17943Hi Kumar,
You can do this like as follows:
List<Account> accounts = [
SELECT
Id
FROM
Account
];Set<Id> accountIds = new Set<Id>();
for(Account acc:accounts){
accountIds.add(acc.Id);
}Thanks
January 2, 2018 at 12:37 pm #23137In addition to Susant anwer, you can also use this code.
Map<Id, Account> mpAccounts = new Map<Id,Account>([Select id, name from Account]);
You can use mpAccounts.keyset() which will give you a set collection of Ids. - AuthorPosts