Print a multidimensional array in C#
In the previous post, we have seen how to print single-dimensional arrays in C#. This post will discuss how to print multidimensional arrays in C#.
1. Using foreach loop
The foreach statement provides a simple, clean way to iterate through the elements of a multidimensional array. The following example shows the usage of the foreach statement for printing multidimensional arrays in C#.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; public class Example { public static void Main() { int[,] array = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } }; foreach (int i in array) { Console.Write("{0} ", i); } } } /* Output: 1 2 3 4 5 6 */ |
However, with multidimensional arrays, using a nested for-loop gives you more control over the order in which to process the array elements.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
using System; public class Example { public static void Main() { int[,] array = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } }; for (int i = 0; i < array.GetLength(0); i++) { for (int j = 0; j < array.GetLength(1); j++) { Console.Write("{0} ", array[i, j]); } Console.WriteLine(); } } } /* Output: 1 2 3 4 5 6 */ |
2. Using String.Join() method
Another good alternative is to use the String.Join() method, which concatenates the elements of the specified array using the specified separator.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; public class Example { public static void Main() { int[,] array2D = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; Console.WriteLine(String.Join(" ", array2D.Cast<int>())); } } /* Output: 1 2 3 4 5 6 */ |
3. Using List.ForEach() method
Another approach is to use the ToList() method to convert the multidimensional array into a generic List<T> and call List’s ForEach() method to print each element of the list. Note that this approach includes creating the list as an intermediate step, which is not recommended.
For multidimensional arrays, we can cast the source sequence elements to the specified type, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { int[,] array = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; List<int> nums = array.Cast<int>().ToList(); nums.ForEach(Console.WriteLine); } } /* Output: 1 2 3 4 5 6 */ |
That’s all about printing a multi-dimensional array in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)