+ Start a Discussion
Rajneesh Ranjan 23Rajneesh Ranjan 23 

Get two fields in a MAP returned by a SOQL without iterating over LIST returned by SOQL

Is it possible to create a MAP<Field1, Field2> directly using SOQL [SELECT Field1, Field2 from Obj_Test] without iterating over LIST returned by SOQL.

For example, if I have an Employee object and want to create a MAP<Emp_Id, Emp_Salary> by using SOQL- SELECT Emp_Id, Emp_Salary FROM Employee__c; I know we can achieve it by using for loop over List returned by SOQL and put these two fields in a map.

Can anyone please let me know if is there another way to do this?

Thanks,
Rajneesh
Deepak GulianDeepak Gulian

I guess no, except this
MAP<Emp_Id, Emp_Salary> empMap = new MAP<Emp_Id, Emp_Salary>();
for (Employee__c emp : [SELECT Emp_Id, Emp_Salary FROM Employee__c]) {
emp.put(emp.Emp_Id, emp.Emp_Salary);
}

Michał Zadrużyński 2Michał Zadrużyński 2
Yes, but only with object Id -> object, any other field as key requires iteration over list.
Map<Id, Employee__c> mapIdToEmplyee = new Map<Id, Emplyee__c>([SELECT Id, Emp_Salary FROM Employee__c]);

 
venkat-Dvenkat-D
It will not make much difference with the way you have map. If you want salary you can do map.get(Emp.Id).Salary__c to get salary with the same map.