Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any utility to print out array directly? [closed]

Tags:

c#

.net

I have an array, I am wondering any utility to print out array directly?

like image 422
Adam Lee Avatar asked Jan 21 '12 15:01

Adam Lee


4 Answers

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 ", ".

like image 182
Sergey Kalinichenko Avatar answered Oct 08 '22 10:10

Sergey Kalinichenko


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) );
like image 28
parapura rajkumar Avatar answered Oct 08 '22 09:10

parapura rajkumar


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.)

like image 30
Des Horsley Avatar answered Oct 08 '22 08:10

Des Horsley


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);
            }
        }
    }
}
like image 27
Soundararajan Avatar answered Oct 08 '22 09:10

Soundararajan