I have an array, I am wondering any utility to print out array directly?
You can use string's Join()
method, like this:
Console.WriteLine("My array: {0}",
string.Join(", ", myArray.Select(v => v.ToString()))
);
This will print array elements converted to string
, separated by ", "
.
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) );
I like @dasblinkenlight solution, but I'd like to note that the select statement is not nessasary.
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));
I find it a little easier on the eyes having less code to read.
(linqpad is a fantastic app to test snippets of code like this.)
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);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With