.NET equivalent of java.util.Arrays.toString (...) methods in Java

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

Is there an equivalent method / functionality in .NET?

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

+3
source share
2 answers

String.Join .

[You will need to add the square brackets yourself]

+3

. NULL, . , .ToElementString() .

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

, ( ). .

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();
}
+1

Source: https://habr.com/ru/post/1704422/


All Articles