[SalesForce] Using List/Set in If Statement

Pretty basic question (I think), but after searching for a few hours and trying different things I can't seem to find a solution. Pretty new to Apex, but I do have experience in SQL, Java/C#, and Python so nothing is too foreign to me.

In my trigger on Opportunity I'm doing a check on whether or not the Opportunity Owner belongs to a few specific UserRoleIds. This was my original try:

// Step 1. Create list of Users where the UserRole Name has AE or CM in it
// I originally did this by querying the UserRole object and then the User role but realized that was redundant

List<User> listUsers = [SELECT Id FROM User WHERE UserRole.Name like '%AE%' OR UserRole.Name like '%CM%'];

// other code

for (Opportunity opp : trigger.New) {
// other stuff

if (/*I want to see if opp.OwnerId is in that list/set/SOQL query that I created*/)

My understanding is that you can't really do that type of search on a list in that scenario, so I did something where I converted my list to a set. Problem there is I couldn't figure out how to convert List<User> or Set<User> to Set<Id> and then use set.contains(opp.OwnerId).

My two questions

  1. Can I search if opp.OwnerId is found in a list (either a list of Users or a list of Ids)?
  2. If not, how do I convert a SOQL query/list into the proper Set type; i.e. a Set of Ids or Strings, so that I could then use the contains method?

    I hope that was clear, but I'm trying to understand this at a higher/conceptual level rather than just getting the right code for this specific example.

I suppose another thing to ask is if it's possible to save a SOQL query in a list of Ids or Strings rather than the object you're querying?

Thanks so much!

Dylan

Best Answer

I think perhaps the best way is to search if the opp.OwnerId is in a Map<User> that you can create from the result of your query.

Map<Id,User> userMap = new Map<Id,User>([SELECT Id FROM User WHERE UserRole.Name like '%AE%' OR UserRole.Name like '%CM%']);

Now you can iterate the opportunities and use containsKey() on the map to see if the User is the owner.

for (Opportunity opp : trigger.New) { 
    if (userMap.containsKey(opp.OwnerId)){
        //opp owner is one of your users with the specific role
    }
}

There are a number of cool things you can do converting to and from Lists, Sets and Maps. You can use the addAll() method on a List or a Set, Map.containsKey(), Map.values() and Map.keySet() among other things.

Have a look at the official documentation for Maps, Lists and Sets

Related Topic