Home >Backend Development >C++ >How to Effectively Print Array Contents in C#?
Detailed explanation of C# array content printing method
If you are used to using System.out.print(Arrays.toString(alg.id))
in Java to print arrays, you may be wondering how to achieve the same functionality in C#. Here's a guide on how to do it:
Use foreach loop:
<code class="language-csharp">foreach (var item in yourArray) { Console.WriteLine(item.ToString()); }</code>
This method iterates over each element in the array and prints it to the console using the ToString()
method.
Use extension method:
<code class="language-csharp">yourArray.ToList().ForEach(i => Console.WriteLine(i.ToString()));</code>
This method combines the ToList()
method and the ForEach()
extension method to achieve the same result as a foreach loop.
Single line printing:
If you wish to output the array contents to a single line, you can use the following code:
<code class="language-csharp">Console.WriteLine("[{0}]", string.Join(", ", yourArray));</code>
This method uses the string.Join()
method to concatenate array elements with comma delimiters and then prints the result within square brackets.
Other options:
Alternatively, you can use the Array.ForEach<T>
method to print the array contents:
<code class="language-csharp">Array.ForEach(yourArray, Console.WriteLine);</code>
This method is more efficient as it does not require converting the array to a list.
The above is the detailed content of How to Effectively Print Array Contents in C#?. For more information, please follow other related articles on the PHP Chinese website!