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?

  • I don't think you're going to be able to do this without iteration, whats the problem with that out of interest? Apr 17, 2017 at 8:43
  • 1
    Recently I have to write code to produce a list of name fields so often. All I need is a list of text fields in objects, so I was wondering if there is a way to convert the list of text fields to a list of strings without iteration so I could avoid the for loop and a few lines of code.
    – Saranya
    Apr 17, 2017 at 8:56
  • You are going to need a for loop for this as you require data for each queried record. A foreach loop with the use of an inline query will give you best results for your requirement.
    – TSmith
    Apr 17, 2017 at 9:22

3 Answers 3


This should work:

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

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.

  • This uses for loop. I want to know whether it can be done without for loop.
    – Saranya
    Apr 17, 2017 at 8:33

Do something like this:

string s = [select name from A__c where field__c =: objB.Id ].name; //if it returns only 1 record. 
list<string> lstNames = new list<string>();
string Names = string.join(lstNames,',');
  • I assume that the SOQL will return 1 record
    – Anujit Das
    Apr 17, 2017 at 10:16

Please use below code snippet, it should work fine. Let's assume the object is Account.

List<AggregateResult> accList= [select name from Account group by name]; 
String str = JSON.serialize(accList);
str = str.removeStart('[{"attributes":{"type":"AggregateResult"},"Name":"');
str= str.replace('"},{"attributes":{"type":"AggregateResult"},"Name":"',',');
Str= str.removeEnd('"}]');

  • @saranya : does this help? Apr 19, 2017 at 17:29
  • 1
    I feel quite confident that JSON serialization is going to be significantly less efficient than the for loop. Sep 29, 2020 at 2:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .