C# 有没有直接打印出数组的实用程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8954127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Any utility to print out array directly?
提问by Adam Lee
I have an array, I am wondering any utility to print out array directly?
我有一个数组,我想知道有什么实用程序可以直接打印出数组?
采纳答案by dasblinkenlight
You can use string's Join()method, like this:
您可以使用字符串的Join()方法,如下所示:
Console.WriteLine("My array: {0}",
string.Join(", ", myArray.Select(v => v.ToString()))
);
This will print array elements converted to string, separated by ", ".
这将打印转换为 的数组元素,以string分隔", "。
回答by parapura rajkumar
You can use the following one liner to print an array
您可以使用下面的一个衬垫打印一个数组
int[] array = new int[] { 1 , 2 , 3 , 4 };
Array.ForEach( array , x => Console.WriteLine(x) );
回答by Soundararajan
You can write an extension method something like this
你可以写一个像这样的扩展方法
namespace ConsoleApplication12
{
class Program
{
static void Main(string[] args)
{
var items = new []{ 1, 2, 3, 4, 5 };
items.PrintArray();
}
}
static class ArrayExtensions
{
public static void PrintArray<T>(this IEnumerable<T> elements)
{
foreach (var element in elements)
{
Console.WriteLine(element);
}
}
}
}
回答by Des Horsley
I like @dasblinkenlight solution, but I'd like to note that the select statement is not nessasary.
我喜欢@dasblinkenlight 解决方案,但我想指出 select 语句不是必需的。
This code produces the same result for an array of strings:
此代码为字符串数组生成相同的结果:
string[] myArray = {"String 1", "String 2", "More strings"};
Console.WriteLine("My array: {0}", string.Join(", ", myArray));
I find it a little easier on the eyes having less code to read.
我发现阅读更少代码的眼睛更容易一些。
(linqpadis a fantastic app to test snippets of code like this.)
(linqpad是一个很棒的应用程序来测试这样的代码片段。)

