13

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?

1 Answer 1

20

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());
}
2
  • 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. Commented Jan 29, 2013 at 19:18
  • This will break the order if you have ORDER BY in your SOQL. Commented Sep 12, 2017 at 11:19

You must log in to answer this question.

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