在 C# 中打印数组的所有内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16265247/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:35:09  来源:igfitidea点击:

printing all contents of array in C#

c#.netarrayslinq

提问by Padraic Cunningham

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

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

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

how do I do this in c#?

我如何在 C# 中做到这一点?

采纳答案by Hossein Narimani Rad

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: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):As it is mentioned in other answers it is better to use Array.ForEach<T>method and there is no need to do the ToListstep.

编辑(2019):正如其他答案中提到的那样,最好使用Array.ForEach<T>方法并且不需要执行该ToList步骤。

Array.ForEach(yourArray, Console.WriteLine);

回答by Eric J.

In C# you can loop through the array printing each element. Note that System.Object defines a method ToString(). Any given type that derives from System.Object() can override that.

在 C# 中,您可以循环打印每个元素的数组。请注意 System.Object 定义了一个方法 ToString()。从 System.Object() 派生的任何给定类型都可以覆盖它。

Returns a string that represents the current object.

返回表示当前对象的字符串。

http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx

http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx

By default the full type name of the object will be printed, though many built-in types override that default to print a more meaningful result. You can override ToString() in your own objects to provide meaningful output.

默认情况下,将打印对象的完整类型名称,但许多内置类型会覆盖该默认值以打印更有意义的结果。您可以在自己的对象中覆盖 ToString() 以提供有意义的输出。

foreach (var item in myArray)
{
    Console.WriteLine(item.ToString()); // Assumes a console application
}

If you had your own class Foo, you could override ToString() like:

如果你有自己的类 Foo,你可以像这样重写 ToString():

public class Foo
{
    public override string ToString()
    {
        return "This is a formatted specific for the class Foo.";
    }
}

回答by Matt Greer

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

有很多方法可以做到,其他答案都很好,这是一个替代方案:

Console.WriteLine(string.Join("\n", myArrayOfObjects));

回答by Matthew Watson

If you want to get cute, you could write an extension method that wrote an IEnumerable<object>sequence to the console. This will work with enumerables of any type, because IEnumerable<T>is covariant on T:

如果你想变得可爱,你可以编写一个扩展方法,将一个IEnumerable<object>序列写入控制台。这将适用于任何类型的枚举,因为IEnumerable<T>它在 T 上是协变的:

using System;
using System.Collections.Generic;

namespace Demo
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            string[] array  = new []{"One", "Two", "Three", "Four"};
            array.Print();

            Console.WriteLine();

            object[] objArray = new object[] {"One", 2, 3.3, TimeSpan.FromDays(4), '5', 6.6f, 7.7m};
            objArray.Print();
        }
    }

    public static class MyEnumerableExt
    {
        public static void Print(this IEnumerable<object> @this)
        {
            foreach (var obj in @this)
                Console.WriteLine(obj);
        }
    }
}

(I don't think you'd use this other than in test code.)

(我认为除了在测试代码中之外,您不会使用它。)

回答by Nai

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

最简单的一个,例如,如果你有一个像这样声明的字符串数组 string[] myStringArray = new string[];

Console.WriteLine("Array : ");
Console.WriteLine("[{0}]", string.Join(", ", myStringArray));

回答by Tomasz Gandor

I upvoted the extension method answer by Matthew Watson, but if you're migrating/visiting coming from Python, you may find such a method useful:

我赞成 Matthew Watson 的扩展方法答案,但如果您从 Python 迁移/访问,您可能会发现这样的方法很有用:

class Utils
{
    static void dump<T>(IEnumerable<T> list, string glue="\n")
    {
        Console.WriteLine(string.Join(glue, list.Select(x => x.ToString())));
    }
}

-> this will print any collection using the separator provided. It's quite limited (nested collections?).

-> 这将使用提供的分隔符打印任何集合。它非常有限(嵌套集合?)。

For a script (i.e. a C# console application which only contains Program.cs, and most things happen in Program.Main) - this may be just fine.

对于脚本(即只包含 Program.cs 的 C# 控制台应用程序,并且大多数事情发生在 中Program.Main)- 这可能很好。

回答by Snehal Thakkar

this is the easiest way that you could print the String by using array!!!

这是使用数组打印字符串的最简单方法!!!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace arraypracticeforstring
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] arr = new string[3] { "Snehal", "Janki", "Thakkar" };

            foreach (string item in arr)
            {
                Console.WriteLine(item.ToString());
            }
            Console.ReadLine();
        }
    }
}

回答by fubo

Another approach with the Array.ForEach<T> Method (T[],?Action<T>)method of the Arrayclass

类的Array.ForEach<T> Method (T[],?Action<T>)方法的另一种方法Array

Array.ForEach(myArray, Console.WriteLine);

That takes only one iteration compared to array.ToList().ForEach(Console.WriteLine)which takes two iterations and creates internally a second array for the List(double iteration runtime and double memory consumtion)

array.ToList().ForEach(Console.WriteLine)需要两次迭代并在内部为List(双迭代运行时和双倍内存消耗)创建第二个数组相比,这仅需要一次迭代

回答by TJ Wolschon

Due to having some downtime at work, I decided to test the speeds of the different methods posted here.

由于工作中有一些停机时间,我决定测试这里发布的不同方法的速度。

These are the four methods I used.

这是我使用的四种方法。

static void Print1(string[] toPrint)
{
    foreach(string s in toPrint)
    {
        Console.Write(s);
    }
}

static void Print2(string[] toPrint)
{
    toPrint.ToList().ForEach(Console.Write);
}

static void Print3(string[] toPrint)
{
    Console.WriteLine(string.Join("", toPrint));
}

static void Print4(string[] toPrint)
{
    Array.ForEach(toPrint, Console.Write);
}

The results are as follows:

结果如下:

Strings per trial: 10000 Number of Trials: 100 Total Time Taken to complete: 00:01:20.5004836 Print1 Average: 484.37ms Print2 Average: 246.29ms Print3 Average: 70.57ms Print4 Average: 233.81ms

Strings per trial: 10000 Number of Trials: 100 Total Time Taken to complete: 00:01:20.5004836 Print1 Average: 484.37ms Print2 Average: 246.29ms Print3 Average: 70.57ms Print4 Average: 233.81ms

So Print3 is the fastest, because it only has one call to the Console.WriteLinewhich seems to be the main bottleneck for the speed of printing out an array. Print4 is slightly faster than Print2 and Print1 is the slowest of them all.

所以 Print3 是最快的,因为它只有一次调用 ,Console.WriteLine这似乎是打印出数组速度的主要瓶颈。Print4 比 Print2 稍快,Print1 是其中最慢的。

I think that Print4 is probably the most versatile of the 4 I tested, even though Print3 is faster.

我认为 Print4 可能是我测试过的 4 个中最通用的,尽管 Print3 更快。

If I made any errors, feel free to let me know / fix them on your own!

如果我犯了任何错误,请随时告诉我/自行修复它们!

EDIT: I'm adding the generated IL below

编辑:我在下面添加生成的 IL

g__Print10_0://Print1
IL_0000:  ldarg.0     
IL_0001:  stloc.0     
IL_0002:  ldc.i4.0    
IL_0003:  stloc.1     
IL_0004:  br.s        IL_0012
IL_0006:  ldloc.0     
IL_0007:  ldloc.1     
IL_0008:  ldelem.ref  
IL_0009:  call        System.Console.Write
IL_000E:  ldloc.1     
IL_000F:  ldc.i4.1    
IL_0010:  add         
IL_0011:  stloc.1     
IL_0012:  ldloc.1     
IL_0013:  ldloc.0     
IL_0014:  ldlen       
IL_0015:  conv.i4     
IL_0016:  blt.s       IL_0006
IL_0018:  ret         

g__Print20_1://Print2
IL_0000:  ldarg.0     
IL_0001:  call        System.Linq.Enumerable.ToList<String>
IL_0006:  ldnull      
IL_0007:  ldftn       System.Console.Write
IL_000D:  newobj      System.Action<System.String>..ctor
IL_0012:  callvirt    System.Collections.Generic.List<System.String>.ForEach
IL_0017:  ret         

g__Print30_2://Print3
IL_0000:  ldstr       ""
IL_0005:  ldarg.0     
IL_0006:  call        System.String.Join
IL_000B:  call        System.Console.WriteLine
IL_0010:  ret         

g__Print40_3://Print4
IL_0000:  ldarg.0     
IL_0001:  ldnull      
IL_0002:  ldftn       System.Console.Write
IL_0008:  newobj      System.Action<System.String>..ctor
IL_000D:  call        System.Array.ForEach<String>
IL_0012:  ret   

回答by Johnny

Starting from C# 6.0, when $- string interpolation has been introduced, there is one more way:

C# 6.0 开始,当引入$- 字符串插值时,还有一种方法:

var array = new[] { "A", "B", "C" };
Console.WriteLine($"{string.Join(", ", array}");

//output
A, B, C

Concatenation could be archived using the System.Linq, convert the string[]to char[]and print as a string

可以使用 将串联存档System.Linq,将其转换string[]char[]并打印为string

var array = new[] { "A", "B", "C" };
Console.WriteLine($"{new String(array.SelectMany(_ => _).ToArray())}");

//output
ABC