printing all contents of array in C#

2019-01-02 18:29发布

I am trying to print out the contents of an array after invoking some methods which alter it, in Java I use:

System.out.print(Arrays.toString(alg.id));

how do I do this in c#?

9条回答
怪性笑人.
2楼-- · 2019-01-02 19:05

The easiest one e.g. if you have a string array declared like this string[] myStringArray = new string[];

Console.WriteLine("Array : ");
Console.WriteLine("[{0}]", string.Join(", ", myStringArray));
查看更多
听够珍惜
3楼-- · 2019-01-02 19:06

You may try this:

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

Also you may want to try something like this:

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

EDIT: Or as suggested in comments:

yourArray.ToList().ForEach(Console.WriteLine);

EDIT: to get output in one line [based on your comment]:

 Console.WriteLine("[{0}]", string.Join(", ", yourArray));
 //output style:  [8, 1, 8, 8, 4, 8, 6, 8, 8, 8]
查看更多
伤终究还是伤i
4楼-- · 2019-01-02 19:07

There are many ways to do it, the other answers are good, here's an alternative:

Console.WriteLine(string.Join("\n", myArrayOfObjects));
查看更多
登录 后发表回答