Contents[Hide]

SOQL query return type

Simple query like

[SELECT id, Name, type__c FROM my_custom_object__c WHERE type__c = :variableWithTypeName]

always returns a list of my_custom_object__c records. List <my_custom_object__c>.

Most common mistake

Your first idea may be to write something like that:

// Variables
Map<Id, my_custom_object__c> filteredRecordsMap = new Map<Id, my_custom_object__c> (); 

// when it is needed to fill in data.
filteredRecordsMap = [SELECT id, Name, type__c FROM my_custom_object__c WHERE type__c = :variableWithTypeName]

then you will see:

Error: my_page_Controller Compile Error: Illegal assignment from LIST<my_custom_object__c> to MAP<Id,my_custom_object__c> at line 60 column 9

that's not possible as List can not be assigned to Map.

Solution 1 - putAll values from List

Quick look at Map methods gives us a hint. There is putAll() method which take as argument sObject[] it's equally to List<my_custom_object__c>.
As pinted in first paragraph SOQL query returns List<my_custom_object__c> so we can use that toggether.

// Variables
Map<Id, my_custom_object__c> filteredRecordsMap = new Map<Id, my_custom_object__c> (); 

// when it is needed to fill in data.
filteredRecordsMap.putAll([SELECT id, Name, type__c FROM my_custom_object__c WHERE type__c = :variableWithTypeName]);

Solution 2 - iterate throught List with optional value modification.

This is usefull when you want to modify values retrived from query. Let say that I want to have all names as UPPERCASE.
See new string methods avaliable since Winter '13

// Variables
List<my_custom_object__c> filteredRecordsList = new List<my_custom_object__c> ();
Map<Id, my_custom_object__c> filteredRecordsMap = new Map<Id, my_custom_object__c> ();

// Fill in wih data
filteredRecordsList = [SELECT id, Name, type__c FROM my_custom_object__c WHERE type__c = :variableWithTypeName];
    
for (my_custom_object__c oneRecord : filteredRecordsList) {
    oneRecord.Name = oneRecord.Name.toUppercase(); // Change all cases to UPPER
    filteredRecordsMap.put(oneRecord.Id, oneRecord); // Fill in Map
}

You may separate variable definition from its initialization:

// Variable Map<Id, my_custom_object__c> filteredRecordsMap; // Initialization when needed filteredRecordsMap = new Map<Id, my_custom_object__c> ( [SELECT id, Name, type__c FROM my_custom_object__c WHERE type__c = :variableWithTypeName]);

This is not recomended as if you call variable filteredRecordsMap before initialization line you will get nullpointer error.


 

 

   
© Paweł Woźniak