Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list of objects to string in one line

Tags:

I have a list of objects that implement ToString(). I need to convert the whole list to one string in one line. How can I do that?

like image 521
user1306322 Avatar asked Jan 02 '13 17:01

user1306322


People also ask

How do I turn a list of objects into strings?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

Can we convert list to String in Java?

We use the toString() method of the list to convert the list into a string.

Can you convert Object to String?

We can convert Object to String in java using toString() method of Object class or String. valueOf(object) method. You can convert any object to String in java whether it is user-defined class, StringBuilder, StringBuffer or anything else.


2 Answers

Another method that may help out is string.Join(), which takes a set of objects and will join them with any delimiter you want. For instance:

var combined = string.Join(", ", myObjects); 

will make a string that is comma/space separated.

like image 141
eouw0o83hf Avatar answered Sep 22 '22 18:09

eouw0o83hf


Assuming you mean your objects implement ToString, I believe this will do it:

String.Concat( objects.Select(o=>o.ToString()) ); 

As per dtb note, this should work as well:

String.Concat( objects ); 

See http://msdn.microsoft.com/en-us/library/dd991828.aspx

Of course, if you don't implement ToString, you can also do things like:

String.Concat( objects.Select(o=>o.FirstName + " " + o.LastName) ); 
like image 40
AaronLS Avatar answered Sep 20 '22 18:09

AaronLS