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
Release: 2025-01-20 19:59:13
Original
843 people have browsed it

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:

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

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:

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

3. Array.ForEach method:

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

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

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:

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

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 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