在 C# 中打印数组的所有内容 [英] printing all contents of array in C#

查看:99
本文介绍了在 C# 中打印数组的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调用一些改变数组的方法后,我试图打印出数组的内容,在我使用的 Java 中:

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

如何在 C# 中执行此操作?

how do I do this in c#?

推荐答案

你可以试试这个:

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

在一行中获得输出[根据您的评论]:

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]

EDIT(2019): 正如其他答案中提到的那样,最好使用 Array.ForEach 方法,而无需执行 ToList 步骤.

EDIT(2019): As it is mentioned in other answers it is better to use Array.ForEach<T> method and there is no need to do the ToList step.

Array.ForEach(yourArray, Console.WriteLine);

这篇关于在 C# 中打印数组的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆