How to effectively print the contents of an array after calling a C# method?
When dealing with arrays in C#, it is often necessary to print its contents after applying various modification methods. This is different from Java, which can use Arrays.toString()
tools.
The following are several ways to print the contents of an array in C#:
<code class="language-csharp">foreach (var item in yourArray) { Console.WriteLine(item.ToString()); }</code>
This code iterates over each element in the array and prints its string representation.
<code class="language-csharp">yourArray.ToList().ForEach(i => Console.WriteLine(i.ToString()));</code>
This method uses LINQ to convert the array to a list and then applies a lambda expression to print the string representation of each element.
For concise single-line output, use:
<code class="language-csharp">Console.WriteLine("[{0}]", string.Join(", ", yourArray));</code>
This method formats the contents of the array into a string enclosed by "[" and "]".
Also, consider using the Array.ForEach<T>
method:
<code class="language-csharp">Array.ForEach(yourArray, Console.WriteLine);</code>
This method avoids converting arrays into lists and improves efficiency.
The above is the detailed content of How to Effectively Print Array Contents in C# After Method Calls?. For more information, please follow other related articles on the PHP Chinese website!