0

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
1

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.

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

Do something like this:

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

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('"}]');

system.debug('Names='+str);
  • @saranya : does this help? – Subhasis Kar Apr 19 '17 at 17:29

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.