Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I'm trying to populate a list of Ids using a soql query but can't seem to get there.

Currently I have:

Public List <Id> listOfGroupIds (id userId) {
    List <Id> returnListOfPublicGroupIds = new List <Id>();
    List <GroupMember> groupMemberList = 
        [SELECT GroupId FROM GroupMember WHERE UserOrGroupId = : userId];
    for (GroupMember gm : groupMemberList) {
        returnListOfPublicGroupIds.add (gm.GroupId);
    }
    return returnListOfPublicGroupIds;
}

but I would like to do something more along the lines of

Public List <Id> listOfGroupIds (id userId) {
    List <Id> returnListOfPublicGroupIds = new List <Id>();
    return returnListOfPublicGroupIds = 
        [SELECT GroupId FROM GroupMember WHERE UserOrGroupId = : userId].GroupId;
}

The error is telling me I am assigning an id to a list of ids. Is there a way to populate this list without the for loop?

share|improve this question

1 Answer 1

up vote 11 down vote accepted

Unfortunately there is no shortcut to building a list of IDs from a SOQL query like you want. The way you are currently building the list is correct when you need to build a list of IDs that are not the primary key.

But maybe something like this will work for you:

public List<Id> listOfGroupIds(Id userId) {
  Map<Id, Group> groupsById = new Map<Id, Group>([
    SELECT Id
    FROM Group
    WHERE Id IN (
      SELECT GroupId
      FROM GroupMember
      WHERE UserOrGroupId = :userId
    )
  ]);

  return new List<Id>(groupsById.keySet());
}
share|improve this answer
    
Thanks for this! I'm trying to find out which would be the quickest way to return the results and only had the for loop option to try before your response. –  Jonathan Jenkins Jan 29 '13 at 19:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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