Aligning text output by the console?

user1172635 picture user1172635 · Apr 24, 2012 · Viewed 8.3k times · Source

What I want to do, is make the text that I output via the Console.Writeline method line up perfectly regardless of length.

Example:
// Notice that no matter the length of the text on the left, 
// the text on the right is always spaced at least 5 spaces.

    this is output          text
    this is also output     text
    output                  text
    my output               text

Am I going to have to write my own method for this, or does .Net contain something that I can use already?

Answer

ΩmegaMan picture ΩmegaMan · Apr 24, 2012

Think in Linq instead!

var outputs = new List<string>() {
                        "this is output",
                        "this is also output",
                        "output",
                        "my output"
                    };

var size = outputs.Max (str => str.Length) + 5;

Console.WriteLine ( 
           string.Join(Environment.NewLine, 
                       outputs.Select (str => str.PadRight( size ) + "Text" ) )
                   );

/*
this is output          Text
this is also output     Text
output                  Text
my output               Text
*/