Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Join on a list of objects

Tags:

c#

list

In C#, if I have a List<MyObj> where MyObj is a custom class with an overridden ToString() method such that each MyObj object in the List can be easily converted to a string.

How can I join this List<MyObj> with a delimiter, such as for example a pipe (|) into a single string.

So, if I had 3 MyObj objects whose ToString methods would produce AAA, BBB, CCC respectively. I would create a single string: AAA|BBB|CCC.

For a list of a simpler type, such as List<string>, I perform this simply as: String.Join("|", myList.ToArray());. Is there a way I can do something similar to that? Or am I forced to iterate over the Object List and use a StringBuilder to append each object's ToString in the list together?

like image 638
user17753 Avatar asked May 10 '12 19:05

user17753


People also ask

How do you join list objects?

The most Pythonic way to concatenate a list of objects is the expression ''. join(str(x) for x in lst) that converts each object to a string using the built-in str(...) function in a generator expression. You can concatenate the resulting list of strings using the join() method on the empty string as a delimiter.

How do you join a list of strings in Python?

If you want to concatenate a list of numbers ( int or float ) into a single string, apply the str() function to each element in the list comprehension to convert numbers to strings, then concatenate them with join() .

What does string Join do C#?

The Join() method in C# is used to concatenate all the elements of a string array, using the specified separator between each element.

What is string join?

Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, using the specified separator between each element.


2 Answers

In .NET 4, you could just use:

var x = string.Join("|", myList);

.NET 3.5 doesn't have as many overloads for string.Join though - you need to perform the string conversion and turn it into an array explicitly:

var x = string.Join("|", myList.Select(x => x.ToString()).ToArray());

Compare the overloads available:

  • .NET 3.5
  • .NET 4
like image 187
Jon Skeet Avatar answered Oct 21 '22 03:10

Jon Skeet


Thank you, Jon Skeet. For a more complex object I use the below:

string.Join("-", item.AssessmentIndexViewPoint.Select(x =>
              x.ViewPointItem.Name).ToList())
like image 20
Shojaeddin Avatar answered Oct 21 '22 01:10

Shojaeddin