[SalesForce] Converting a list of objects to a list of string without iteration

I need a comma separated list of Names of a custom object. I tried the below code.

List<string> lstNames = new List<string>();
lstNames = [Select Name from A__c where field__c =: objB.Id ];
string Names = string.join(lstNames,',')

It gives me an error that Illegal assignment from List to List. I know it is because I am trying to convert a list of A__c to a list of string. Is there a way available to convert a list of object to a list of string without iterating through each record or to get a comma separated list of values without iteration?

Best Answer

This should work:

List<String> lstNames = new List<String>();
for(A__c ac: [Select Name from A__c where field__c =: objB.Id]){
    lstNames.add(ac.Name);
}
String names = string.join(lstNames,',');
System.debug(names);

Your code not works because you are trying to assign an object to a string.

-edit In my opinion, this is not possible without loop.

Related Topic