I want to create a list that uses a a custom object called Animal__c and I want the list to consist of only Dogs, i have a field called 'species__c' which is text based, all the animals in Animal__c are either 'Dog' or 'Cat'. How do i make this, I am relatively new to Apex, and the tutorials on lists are not helping me out too much. Thanks in advanced

  • 1
    Apex/soql question, or reporting ? Jul 16, 2014 at 18:43

1 Answer 1


Jordan, Welcome to SFSE.

1) How to work with Lists in salesforce : https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_list.htm

2) create a list that uses a a custom object called Animal__c

Approach 1:

Advantage: Very specific query helps the system to get selective records instead of pulling all the records from animal object.

Disadvantage: Too specific that you need to alter your query/ add another query to pull Cat/Tiger species

//Create a new list of animal__c to hold just Dog species.
List<animal__c> Dog_list = new List<animal__c>();

//Query the existing database to get only dogs 
Dog_list = [select species__c from animal__c where species__c =: 'Dog'];


Approach 2:

Advantage: Query is more wide with no where filters there by you can add more if conditions and create a cat_List or Tiger_list without having to use more queries.

Disadvantage: Very slow system when you have too many records in the animal object.

// Query the Database and get all species in the animal object.
List<animal__c> All_animal_list = [select species__c from animal__c];
//Iterate through each animal in your list 
for(animal__c animal : All_animal_list ){
    //Check if species of each animal == Dog
    if(animal.species__c == 'Dog'){
       //add the animal to the Dog_list.

Best route:

1) Use where clause to make your query selective based on your needs eg: you need a list for cats and one for dogs

List<animal__c> cat_list = new List<animal__c>();
List<animal__c> dog_list = new List<animal__c>();
List<animal__c> all_species_list = new List<animal__c>();
String[] all_species_I_Need = new String[]{'Cat', 'Dog'};

all_species_list  = [select species__c from animal__c where species__c IN: all_species_I_Need];

for(animal__c animal : all_species_list){
if(animal.species__c == 'Dog'){
else if( animal.species__c == 'Cat'){

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.