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:
foreach (var item in yourArray) { Console.WriteLine(item.ToString()); }
For a more concise approach, a lambda expression provides an alternative:
yourArray.ToList().ForEach(i => Console.WriteLine(i.ToString()));
To output all array elements on a single line, separated by commas, utilize string.Join
:
Console.WriteLine("[{0}]", string.Join(", ", yourArray));
For optimal performance, however, the Array.ForEach<T>
method is preferred, avoiding the overhead of list conversion:
Array.ForEach(yourArray, Console.WriteLine);
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!