10

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?

16

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());
}
|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
  • This will break the order if you have ORDER BY in your SOQL. – Oles Malkov Sep 12 '17 at 11:19

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.