printing all contents of array in C#
Solution 1
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 ToList
step.
Array.ForEach(yourArray, Console.WriteLine);
Solution 2
There are many ways to do it, the other answers are good, here's an alternative:
Console.WriteLine(string.Join("\n", myArrayOfObjects));
Solution 3
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));
Solution 4
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
Solution 5
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)
Comments
-
Padraic Cunningham about 2 years
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#?
-
Eren Ersönmez about 11 yearsNote that .ToString is not necessary since WriteLine has various overloads including a fallback one that takes an Object.
-
Padraic Cunningham about 11 yearsI used alg.Id.ToList().ForEach(Console.WriteLine), that worked well thanks you. Is it possible to actually print it like: [8, 1, 8, 8, 4, 8, 6, 8, 8, 8]
-
Hossein Narimani Rad about 11 years@ErenErsönmez Yes. You are right. but what if the item was a custom class with its own
ToString
mechanism. -
Padraic Cunningham about 11 yearsTook me a while to fully understand but that is very handy, I am used to Python and putting print statements in to help debug so this is good for me.Thanks
-
Miguel Gamboa about 8 yearsOn
ForEach
approach use:expected.ToList().ForEach(Console.WriteLine);
You may use a Method Reference instead of a lambda that will create a new useless anonymous method. -
Daxtron2 almost 6 yearsI like your method the best, it's the second fastest as per my test but it's more versatile than the fastest method( in my opinion ).
-
juharr over 4 yearsCreating a list with
ToList
just to use theForEach
method is a horrible practice IMHO. -
fubo over 4 yearsanyway there is no need to copy and paste my answer into yours
-
Teo about 4 yearsI like this because fits well for me in a write to log:e.g. myArrayObjects is _validExtensions: Write2Log("Start blabla with the exenstions: " + string.Join("-", _validImgExtensions) + " and so on");
-
Aaron over 3 yearsI like this too as it fits well with logging; And if the array element is one of your objects you can override the
ToString()
and handle the formatting there.var a = new [] { "Admin", "Peon" };_log.LogDebug($"Supplied roles are '{string.Join(", ", a)}'.");
-
toughQuestions over 3 yearsWhat if the array is very big? Is there an easy way to split the one liner into multiple more readable lines? Thanks