1

I have a real quick question.

Usually when I want to get a list of IDs as a List i'll do something like:

List<String> voterIds = [select ID, from Vote__c where suggestion__c =: recordId].ID;

But for some reason when I try to do it this time I am getting an "Illegal assignment from Id to List"

Can anyone provide some insight into this? I'll be happy to supply code if necessary, thanks in advance!

1

2 Answers 2

4

The current syntax you have is incorrect. You dereference a field when you know that your query will return only one record. This is what seems to be the case here where you are dereferencing the ID field and thus it is always assumed that there is one record returned from the query, which you are trying to assign to a List, resulting in the error.

The correct syntax here should be as:

Id voterId = [select ID from Vote__c where suggestion__c =: recordId LIMIT 1].ID;

If you want to get the List of ids, then you should have something as below (there are other approaches too) and then get the Id of the records:

List<Vote__c> voterIds = [select ID from Vote__c where suggestion__c =: recordId];
List<Id> idList = new List<Id>();
for(Vote__c v : voterIds) {
    idList.add(v.Id);
}
6

As it says, you're trying to assign an Id (a scalar value) to a collection. You need a loop for this:

Id[] voterIds = new Id[0];
for(Vote__c record: [SELECT Id FROM Vote__c WHERE Suggestion__c = :recordId]) {
  voterIds.add(record.Id);
}

Or, my favorite choice for getting a list of ID values, using a Map to get the values all at once:

Set<Id> voterIds = new Map<Id, Vote__c>([
  SELECT Id FROM Vote__c WHERE Suggestion__c = :recordId
]).keySet();

You must log in to answer this question.

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