Any utility to print the array directly?

I have an array, I'm wondering what utility to print the array directly?

+6
source share
4 answers

You can use the string Join() method, for example:

 Console.WriteLine("My array: {0}", string.Join(", ", myArray.Select(v => v.ToString())) ); 

This will print the elements of the array converted to string , separated by ", " .

+18
source

You can use the following one liner to print an array

 int[] array = new int[] { 1 , 2 , 3 , 4 }; Array.ForEach( array , x => Console.WriteLine(x) ); 
+9
source

I like @ dasblinkenlight's solution, but I would like to point out that the select statement is optional.

This code produces the same result for an array of strings:

 string[] myArray = {"String 1", "String 2", "More strings"}; Console.WriteLine("My array: {0}", string.Join(", ", myArray)); 

It seems to me that a little easier on the eyes than less code to read.

( linqpad is a fantastic application for testing code snippets like this.)

+3
source

You can write an extension method something like this

 namespace ConsoleApplication12 { class Program { static void Main(string[] args) { var items = new []{ 1, 2, 3, 4, 5 }; items.PrintArray(); } } static class ArrayExtensions { public static void PrintArray<T>(this IEnumerable<T> elements) { foreach (var element in elements) { Console.WriteLine(element); } } } } 
+2
source

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


All Articles