6

I want to get a map of rate_code and ID instead of Id and Rate object directly from SOQL query.

If i run following query then i will have to iterate over rateMap map to create Map<String rate_code , String ID>. Is there any other efficient way to get this kind of result directly using soql OR by doing minimal manipulations in apex code ?

Map<String, Rate> rateMap = [select id, rate_code from Rate];
  • 5
    I fear that you have to do it by iterating over the result. There is no "direct" method to do the same – Avidev9 Dec 3 '13 at 11:00
  • 7
    Check out this question for the code. – Peter Knolle Dec 3 '13 at 11:15
7

The code below would be the simplest way to do it using a for each loop. It will stop you hitting a heap size limit if you are iterating over a lot of records, which you could potentially be doing as there is no where condition on your SOQL.

Map<String, Id> rateMap = new Map<String, Id>();    
for (Rate r : [select Id, rate_code from Rate]) {
    rateMap.put(r.rate_code, r.Id);
}

Also keep in mind that your rate_code may not be unique and potentially cause Rates to be excluded from the map. Map<String, List<Id>> may be a better way.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.