Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing all contents of array in C#

Tags:

arrays

c#

.net

linq

I am trying to print out the contents of an array after invoking some methods which alter it, in Java I use:

System.out.print(Arrays.toString(alg.id)); 

how do I do this in c#?

like image 963
Padraic Cunningham Avatar asked Apr 28 '13 16:04

Padraic Cunningham


People also ask

Can you print whole array in C?

This program will let you understand that how to print an array in C. We need to declare & define one array and then loop upto the length of array. At each iteration we shall print one index value of array.

What is the syntax to print all the elements of an array?

Reference Elements To reference a single element, we are required to know the index number of the element. We can reference or print any element using the following syntax: ${ARRAY_NAME[index]}

How do you find the total elements of an array?

Just divide the number of allocated bytes by the number of bytes of the array's data type using sizeof() . int numArrElements = sizeof(myArray) / sizeof(int);


1 Answers

You may try this:

foreach(var item in yourArray) {     Console.WriteLine(item.ToString()); } 

Also you may want to try something like this:

yourArray.ToList().ForEach(i => Console.WriteLine(i.ToString())); 

EDIT: to get output in one line [based on your comment]:

 Console.WriteLine("[{0}]", string.Join(", ", yourArray));  //output style:  [8, 1, 8, 8, 4, 8, 6, 8, 8, 8] 

EDIT(2019): As it is mentioned in other answers it is better to use Array.ForEach<T> method and there is no need to do the ToList step.

Array.ForEach(yourArray, Console.WriteLine); 
like image 178
Hossein Narimani Rad Avatar answered Sep 25 '22 17:09

Hossein Narimani Rad