List.contains in not working

  • I have to get subset of users who do not have records in custom table last modified in last 15 minutes. Here is my code:

    string query = 'Select Id FROM MyCustomObject__c where LastModifiedDate > ' + Datetime.now().addMinutes(15);
    
    List<MyCustomObject__c> sobjList = Database.query(query);
    
    List<String> userIdsToRemove = new List<String>();
    for (MyCustomObject__c dataGrid :sobjList)
    {
        userIdsToRemove.Add(dataGrid.Id);
    }
    
    List<User> allUsers = [select Id FROM User WHERE Profile.UserLicense.Name IN ('Salesforce','Salesforce Platform') AND 
                        IsActive=TRUE];
    for (User u :allUsers)
    {
        if (!userIdsToRemove.contains(u.Id))
        {
            usersToUpdate.Add(u);
        }
    }
    

    I get the following error: Error: Compile Error: Method does not exist or incorrect signature: [List].contains(Id) Why is my code complaining about contains()? Is there a way to optimize this code

  • The List class does not have a contains method. Use the Set class instead:

    Set<Id> userIdsToRemove = new Set<Id>();
    if (!userIdsToRemove.contains(u.Id)) { /* do stuff */ }
    

    right on. @user569925 - This is why I always suffix the name of my collection variables as either `....List`, `...Set`, or `....Map` so when I look at / edit the code I know which methods are available to use (given the absence of code complete in my version of the Force.com Eclipse IDE)

    I tend to find the use of suffixes distasteful and use other conventions for that (e.g. `Map` is usually something like `keyToValue`, `parentToChildren`, etc.). However it is a good strategy if confusion is creeping in about which data type is in use.

    Does it not seem utterly ludicrous that such an obvious method is missing?

    @NickJ Yes, it does.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used