Search code examples
listloopsiteratorsalesforceapex-code

Creating a list in Apex


I have made this list and its suppose to return all the users that are active but I dotn know why the for loop is wrong. do I need a Set?

public with sharing class ActiveAgents {

    public ActiveAgents() {
        User U = new User();
        List<User> ActiveUser = [SELECT Name , UserName, LastName
                                 FROM User
                                 WHERE IsActive = true];

        for (User currentUser : ActiveUser){


            U.add(currentUser.Name);
            U.add(currentUser.Username);
        }

    }
} 

Solution

  • If you're just trying to get a list of user name and UserName values you need a set.

    set<String> setUserInfo = new set<String>();
    for(User currentUser : [SELECT Name , UserName, LastName
                                 FROM User
                                 WHERE IsActive = true]){
       setUserInfo.add(currentUser.Name);
       setUserInfo.add(currentUser.UserName);
    }
    

    But it's hard to tell exactly what you are trying to accomplish from your description. But in your code you're only creating 1 User record

    User U = new User();  
    

    So your loop is just resetting the username and name value of your single user object over and over again.

    Also your declaration of the method ActiveAgents is wrong, but I'm assuming this is just some pseudo code.