Need Help to Update the two multiple records at the same time with unique value

apexmap

Hi I am working on the scenario, and need some help from the community, kindly help me out for the below .

I have created a below map in my class : –

Private Map <Id, string> testMap =  new Map <Id, string>();

and i am populating the the map as below with the key and value pair,

for(Test_obj__c sId : listOfObject){
                testMap .put(sId.id, sId.TextField);
             }

Values in the above field as below, printed with the help of system.debug;
]|DEBUG|>>>>>>>>>Required Map as follows in batch in Execute Method== 
{a1f3M000000aSCYQUA3=TestValueA, a1f3M000000aSD7Q8M=TestValue4
}

Question or help needed:– I need to query all the records as per the Key as Id and Update on particular field in the data base,
for example:- a1f3M000000aSCYQUA3–Stored as (sourcetestFiled) with this ID if i have got the 4 records then i need to update the particular field as TestValueA in for all the 4 record and update;

Similarly for the another ID (a1f3M000000aSD7Q8M)

I have done from below approach:-

for(id icId : testMap .keySet()){
            for(Test_obj__c icToUpdate : [select id,TextField, textId__c from Test_obj__c Where textId__c =:icId]){
                icToUpdate.TextField= testMap.get(icId);
                listUpadte.add(icToUpdate);
            }
        }

Update List

I ahve done from the above approach, need some help to do it in the best possible way. thanks

Best Answer

Purpose of your approach is not clear to me. But it can be optimized in following way to remove query inside for loop and nested for loop.

for(Test_obj__c icToUpdate : [select id,TextField, textId__c from Test_obj__c Where textId__c IN : testMap.keySet()]){
    icToUpdate.TextField= testMap.get(icToUpdate.textId__c);
    listUpadte.add(icToUpdate);
}
Related Topic