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? – Phil Hawthorn Apr 17 '17 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 '17 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 '17 at 9:22

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.

| improve this answer | |
  • This uses for loop. I want to know whether it can be done without for loop. – Saranya Apr 17 '17 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,',');
| improve this answer | |
  • I assume that the SOQL will return 1 record – Anujit Das Apr 17 '17 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('"}]');

| improve this answer | |
  • @saranya : does this help? – Subhasis Kar Apr 19 '17 at 17:29
  • I feel quite confident that JSON serialization is going to be significantly less efficient than the for loop. – Tory Netherton Sep 29 at 2:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.