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
TheRightDoctorsTheRightDoctors 

Using batch apex for a complex apex class

I created an apex class to go through all the contacts in 'Contact' object, search for duplicates and later merge them all. This works in sandbox but in production the number of rows are very large so it is not working. So, I want to create a batch apex class which does this task but the present apex code seems a bit complex to convert to batch apex.
 
public List<Contact> getMergeListAll(){
        List<AggregateResult> lastnames = new List<AggregateResult>();
        lastnames = [SELECT LastName FROM Contact GROUP BY LastName HAVING count(Id) > 1 ORDER BY LastName] ;
        String str = '';
        for(AggregateResult A : lastnames){
            if(str == ''){
                str += A.get('N');
            } 
            else{
                str += ',' + A.get('N');
            } 
        }
        List<String> resultNames = str.split(',');
        List<Contact> tempIds = [SELECT Id FROM Contact WHERE LastName IN :resultNames ORDER BY LastName ];
        String str_c = '';
        for(Contact A : tempIds){
            if(str_c == '')
                str_c += A.get('Id') ;
            else
                str_c += ',' + A.get('Id') ;
        }
        List<String> resultIds = str_c.split(',');
        
        return [SELECT Name, FirstName, LastName, Phone, email, MobilePhone, AccountID, Specialty__c, Title, Company__c, Contact_Source__c,
                Call_Status__c, Mail_Status__c, Whatsapp_Status__c, Status__c, Date_of_Birth__c, Website__c, Hospital__c,
                Phone1__c, Extension_Landline__c, Extension_2_Landline_2__c, Phone2__c, Assitant__c, Assistant_Contact_Number__c,
                Call_Date_Time__c, Call_Made_By_name__c, Minutes_of_Meeting_TC__c, MOM__c, Created_Date_Time__c, Created_By_Name__c,
                Fax, SSC_Percentage__c, PUC_Percentage__c, Graduation_Percentage__c, Roll_number__c, Branch__c, Education__c, year__c,
                Candidate_Status__c, Added_to_Ozontel_Campaign__c, Interview_Date__c, Interview_Time__c, Joining_Date__c, Resume_link__c,
                Candidate_Permanent_Address__c, Candidate_Present_Address__c, Internship_Project_Details__c, 
                Experience_Details__c, Skills__c FROM Contact WHERE Id IN :resultIds ORDER BY Name];
    }
    
    public void MergeAll(){

The above function gets all the lastnames that are duplicates and then returns their attributes to another function 'MergeAll()'. My main question is how to return a List of lastnames that are duplicates from batch apex class into the apex class. Any help is appreciated.