Home > Backend Development > C++ > How to Effectively Print Array Contents in C#?

How to Effectively Print Array Contents in C#?

Susan Sarandon
Release: 2025-01-20 19:56:41
Original
439 people have browsed it

How to Effectively Print Array Contents in C#?

Detailed explanation of C# array content printing method

If you are used to using System.out.print(Arrays.toString(alg.id)) in Java to print arrays, you may be wondering how to achieve the same functionality in C#. Here's a guide on how to do it:

Use foreach loop:

foreach (var item in yourArray)
{
    Console.WriteLine(item.ToString());
}
Copy after login

This method iterates over each element in the array and prints it to the console using the ToString() method.

Use extension method:

yourArray.ToList().ForEach(i => Console.WriteLine(i.ToString()));
Copy after login

This method combines the ToList() method and the ForEach() extension method to achieve the same result as a foreach loop.

Single line printing:

If you wish to output the array contents to a single line, you can use the following code:

Console.WriteLine("[{0}]", string.Join(", ", yourArray));
Copy after login

This method uses the string.Join() method to concatenate array elements with comma delimiters and then prints the result within square brackets.

Other options:

Alternatively, you can use the Array.ForEach<T> method to print the array contents:

Array.ForEach(yourArray, Console.WriteLine);
Copy after login

This method is more efficient as it does not require converting the array to a list.

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

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template