Convert list of objects to string in one line

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?

0

5 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.

3

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

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

String.Concat( objects.Select(o=>o.FirstName + " " + o.LastName) );
3

You can use String.Join to concatenate the object list.

string str = String.Join(",", objects);
2

None of these worked for me. I'm confused, because the docs explicitly say they won't work (require string, not object). But modifying @Adil's original answer (found by looking at the previous revisions), I got a version that works fine:

string.Join( ",", objectList.Select(c=>c.ToString()).ToArray<string>())

EDIT: as per @Chris's comment - I'm using Unity's version of .NET. I used the Microsoft docs as reference, so I'm still confused why this got downvoted, but ... maybe it's a Unity-specific problem that needs this solution.

2

You can use Linq Enumerable.Select to select a string object and Enumerable.Aggregate into a string.

string StringConcat = ObjectList.Select(x => { return x.StringValue; }).ToList().Aggregate((a,b) => $"{a},{b}");

Example structure:

ObjectList = List<ObjectClass>();
public class ObjectClass { public string StringValue { get; set; }
}

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like