简体   繁体   中英

Printing all contents from an array in a single line C#

I am wanting to output the whole array in a single line. I know how to do one each line which would be:

Array.ForEach(array1, Console.WriteLine);

I saw that to print it all out in 1 line it is like this:

Console.WriteLine("[{0}]", string.Join(", ", array1));

But i don't really understand what that piece of code is actually doing - If there is a more basic version to understand please let me know, if not then could you please explain what it is doing?

It might help to understand that this code:

Console.WriteLine("{0}", string.Join(", ", array1));

Is pretty much the same as this code:

string allContents = string.Join(", ", array1);
Console.WriteLine(allContents);

Microsoft Docs defines string.Join as follows:

Concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member.

If you ever don't understand what a method does, you can look it up there for some help:)

The "{0}" part of the string is replaced by the first (index 0) argument which comes after it. So in your case, this is the evaluation of "string.Join(", ", array1)". This is known as Composite Formatting, and you can read more about it here .

Basically, when Console.WriteLine encounters numbers (or special formats) enclosed in curly brackets, along with additional objects (which specify the objects to be formatted), then it treats those curly brackets as special characters and it formats the values passed into them accordingly. If you want to actually print the curly bracket characters, then you need to 'escape' them by using "{{" instead of "{", and "}}" instead of "}".This can be demonstrated by testing some variations:

Console.WriteLine("{0} {1} {2} {3} {4}", "this", "is", "a", "test", "string"); // Prints "this is a test string".
Console.WriteLine("{0} {1} {0} {4} {3}", "this", "is", "a", "test", "string"); // Prints "this is this string test" - note you can order the arguments whatever way you like and also reuse them.
Console.WriteLine("{{0}}", string.Join(", ", array1)); // Prints "{0}", as the curly brackets are 'escaped', meaning they are treated literally. The other arguments are ignored as no string contained within curly brackets was detected.
Console.WriteLine("{0}"); // Prints "{0}" exactly as it's written, as there are no arguments to be formatted.
Console.WriteLine("[{asdf}]", string.Join(", ", array1)); // throws an exception, because an invalid format is enclosed in curly brackets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM