5

I am trying to get unique items from an object so I am starting with a set however I need the values to be returned as a list for the visualforce <apex:selectOptions> component. I have tried the code below, and variations, but I keep getting errors related to the type not being set correctly. Can anyone help me out? Is there a better way of populating a list with unique values from a SOQL query?

    public List<SelectOption> getItems() {

        Set<License__c> license = new Set<License__c>( [SELECT Name FROM License__c] );
        List<SelectOption> options = new List<SelectOption>();
            options.addAll(license);
        return options;
}
6

No need to work with lists and sets if you group-by in the query:

    public List<SelectOption> getItems() {
        List<SelectOption> options = new List<SelectOption>();
        for(AggregateResult l : [SELECT Name FROM License__c GROUP BY Name]){ 
            options.add(new SelectOption(String.valueOf(l.get('Name')),String.valueOf(l.get('Name'))));
        }
        return options;
    }
3
  • I like you method the best so far but it is generating an error. – Matt M Jun 9 '16 at 19:02
  • Loop variable must be an SObject or list of AggregateResult – Matt M Jun 9 '16 at 19:02
  • 1
    Ah you're right it has to loop through aggregateresult because of the grouping. I corrected that now. Slightly less clean because we then have to fetch the values and convert to string, although still the most efficient way of doing it I believe – Guy Clairbois Jun 9 '16 at 19:10
6

Simplest way:

new List<String>( new Set<String> {'a', 'b', 'c'} );

1

You need to create a list of SelectOptions. The set you have is not the same type, so you have to iterate over them, and create SelectOption objects, then add them to the list.

for (License__c l: license) {
    options.add(new SelectOption(l.Name, l.Id));
}
0

If you want unique elements, you could tweak your SOQL to get distinct names. Since the DISTINCT keyword is not supported by SOQL, one workaround is to use GROUP

SELECT Name, COUNT(Name) FROM License__c GROUP BY Name

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.