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 18:47

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:

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

查看更多
墨雨无痕
3楼-- · 2019-01-02 18:48

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();
        }
    }
}
查看更多
初与友歌
4楼-- · 2019-01-02 18:59

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

So Print3 is the fastest, because it only has one call to the Console.WriteLine which 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.

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

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

EDIT: I'm adding the generated IL below

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   
查看更多
有味是清欢
5楼-- · 2019-01-02 18:59

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:

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.

查看更多
无与为乐者.
6楼-- · 2019-01-02 19:02

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.

Returns a string that represents the current object.

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.

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:

public class Foo
{
    public override string ToString()
    {
        return "This is a formatted specific for the class Foo.";
    }
}
查看更多
旧时光的记忆
7楼-- · 2019-01-02 19:02

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

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)

查看更多
登录 后发表回答