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?
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.
We use the toString() method of the list to convert the list into a 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.
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.
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) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With