Home >Backend Development >C++ >How to Print an Array's Contents in C#?

How to Print an Array's Contents in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-20 19:59:13834browse

How to Print an Array's Contents in C#?

Several methods of printing array contents in C#

Unlike Java, C# has no direct equivalent to Java's System.out.print(Arrays.toString(alg.id)) method for printing array contents. You can use the following methods:

1. foreach loop:

Use foreach to loop through the array elements and print them one by one:

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

2. Lambda expression combined with ToList:

Alternatively, you can use a Lambda expression to iterate over the array elements and add them to a list, then print the list:

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

3. Array.ForEach method:

In C#, the preferred way to print array elements is to use the Array.ForEach<T> method:

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

This method takes a Lambda expression as a parameter and executes the expression for each element in the array.

4. Single line printing:

If you want to print the array contents in one line, you can use the following format string:

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

This will generate output in the format [<item1>, <item2>, ..., <itemn>].

The above is the detailed content of How to Print an Array's Contents 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