function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Chris Henson2Chris Henson2 

Most efficient way to get Map<String, String> from a SOQL query

Hi All, 

I know there are ways to do what I'm outlining here, but the ones that I know are kind of ugly and involve double for-loops and the like. I'm trying to streamline this code a little, so I'm looking for a more efficient method.  

Desired Functionality:
Taking a SOQL query of a custom metadata object, returning 2 text fields, and comparing this to a list of objects.  If value1 == the object parameter we're looking for, then replace it with  value2.  

Current Code:

(This is currently in the process of being revised, so it currently does not work, and has been 'scrubbed of actual data, so if some syntax is off, it is not the cause of my issue)
List<custObj__c> relatedList = [Select oldValue from custObj__c];

if(relatedList.size() > 0){
         
         //******This is not correct, and does not work*****       
         Map<String, String> z = new Map<String, String>([SELECT value1__c, value2__c FROM X__mdt WHERE isActive__c=True]);     
//*********//
                              
         if(z != null) {
             for(custObject__c related : relatedList){ 
                  if(z.contains(related.oldValue)){
                        related.oldValue = z.get(related.oldValue);                          
                  }
             }
         }
         Database.update(relatedList, true);
}

So the question is: Is there a way to create a Map to use in the manner I'm trying to above that would not involve creating another for-loop to populate it?
Priya GovindasamyPriya Govindasamy
you can do something like this to fetch all fields and its values in a Map.

    public static Map<String,Object> metaData(SObjectType obj, String record) {
        Map<String,Object> returnData = new Map<String,Object>();
        try {
            DescribeSObjectResult DescribeResult = obj.getDescribe();
            List<String> FieldNames = new List<String>( DescribeResult.fields.getMap().keySet() );
            String query = 'SELECT ' + String.join( FieldNames, ',' ) + ' FROM ' + DescribeResult.getName() + ' WHERE DeveloperName = :record Limit 1';
            List<sObject> os = Database.query(query);
            if(null != os && os.size() > 0 ) {
                sObject o = os[0];
                for(String fieldName: FieldNames) {
                    returnData.put(fieldName,(o).get(fieldName));
                }
            }
        }
        catch (Exception e) {
           throw e;
        }
        return returnData;
    }
Team NubesEliteTeam NubesElite
Hi,
Please try like this
Map<String, CustomObject__c> myMap = new Map<String, CustomObject__c>();

Thank You
www.nubeselite.com

Developement | Training | Consulting

Please Mark this as solution if your problem resolved.