Home >Backend Development >C++ >How Can I Efficiently Print Array Elements in C#?
Several Ways to Print C# Array Elements
This article explores efficient methods for displaying the contents of a modified C# array. Several approaches are presented, each offering different advantages.
A straightforward method uses a foreach
loop:
<code class="language-csharp">foreach (var item in yourArray) { Console.WriteLine(item.ToString()); }</code>
For a more concise approach, a lambda expression provides an alternative:
<code class="language-csharp">yourArray.ToList().ForEach(i => Console.WriteLine(i.ToString()));</code>
To output all array elements on a single line, separated by commas, utilize string.Join
:
<code class="language-csharp">Console.WriteLine("[{0}]", string.Join(", ", yourArray));</code>
For optimal performance, however, the Array.ForEach<T>
method is preferred, avoiding the overhead of list conversion:
<code class="language-csharp">Array.ForEach(yourArray, Console.WriteLine);</code>
The above is the detailed content of How Can I Efficiently Print Array Elements in C#?. For more information, please follow other related articles on the PHP Chinese website!