23

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user17753
  • 3,083
  • 9
  • 35
  • 73

2 Answers2

65

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:

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

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

string.Join("-", item.AssessmentIndexViewPoint.Select(x =>
              x.ViewPointItem.Name).ToList())
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shojaeddin
  • 1,851
  • 1
  • 18
  • 16