Home >Backend Development >C++ >How Can I Print the Contents of an Array in C#?

How Can I Print the Contents of an Array in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-20 20:05:15420browse

How Can I Print the Contents of an Array in C#?

Efficiently Displaying C# Array Contents

This guide demonstrates several methods for printing the contents of a C# array, offering alternatives to Java's Arrays.toString() method.

Method 1: foreach Loop

The simplest approach involves a foreach loop:

<code class="language-csharp">foreach (var item in yourArray) {
    Console.WriteLine(item.ToString());
}</code>

This iterates through each element and prints its string representation.

Method 2: Anonymous Function with ForEach

Using LINQ's ForEach with an anonymous function provides a concise solution:

<code class="language-csharp">yourArray.ToList().ForEach(i => Console.WriteLine(i.ToString()));</code>

Note that this method first converts the array to a list, which might be less efficient for very large arrays.

Method 3: Single-Line Output with string.Join

For a compact, single-line output:

<code class="language-csharp">Console.WriteLine("[{0}]", string.Join(", ", yourArray));</code>

This joins array elements with commas and encloses them in square brackets.

Method 4: Array.ForEach (Most Efficient)

The most efficient method leverages the Array.ForEach<T> method:

<code class="language-csharp">Array.ForEach(yourArray, Console.WriteLine);</code>

This directly applies the Console.WriteLine method to each array element, avoiding the overhead of list conversion. This is generally the preferred approach for performance reasons.

The above is the detailed content of How Can I Print the Contents of an Array in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn