How to populate a list of Ids from a soql query without using a for loop?

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?

Answer

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());
}

Attribution
Source : Link , Question Author : Jonathan Jenkins , Answer Author : Alan Morey

Leave a Comment