views:

227

answers:

2

In Java, the java.util.Arrays class have several static toString(...) methods that take an array and return its string representation (i.e. the string representation of the contents of the array separated by commas and the whole representation enclosed in square brackets -- e.g. "[1, 2, 3]").

Is there an equivalent method/functionality in .NET?

I am looking a for method that does this without resorting to manually constructing a loop/method to iterate through the array.

+2  A: 

The String.Join method.

[You will need to add the square brackets yourself]

Mitch Wheat
This solution only works when the array is already of type string.
JaredPar
True. I had assumed that was what was being asked for.
Mitch Wheat
@Mitch, based on the [1, 2, 3] example I thought he was looking for a more general solution. But he accepted yours so I had it backwards.
JaredPar
+1  A: 

Try this. It won't handle NULL values but it will work against value types and reference types. Because it's an extension method you can just call .ToElementString() on any array instance.

public static string ToElementString<T>(this T[] array) {
  var middle = array.Select(x => x.ToString().Aggregate((l,r) => l+","+r);
  return "[" + middle + "]";
}

Here is a version which uses a builder and will potentially be a bit more efficient (only a profiler knows for sure). It will also properly handle null values.

public static string ToElementString<T>(this T[] array) {
  var builder = new StringBuilder();
  builder.Append('[');
  for(int i =0; i < array.Length; i++ ) {
    if ( i > 0 ) {
      builder.Append(',');
    }
    builder.Append(array[i]);
  }
  builder.Append(']');
  return builder.ToString();
}
JaredPar