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()); }
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()));
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);
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));
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!