How to print List as table in console application?
The easiest this you can do is to use an existing library
Install-Package ConsoleTables
And then you can define your table like so:
ConsoleTable.From<Order>(orders).Write();
And it will give this output
| Id | Quantity | Name | Date |
|----------|----------|-------------------|---------------------|
| 3355 | 6 | Some Product 3355 | 18-04-2016 00:52:52 |
| 3355 | 6 | Some Product 3355 | 18-04-2016 00:52:52 |
| 3355 | 6 | Some Product 3355 | 18-04-2016 00:52:52 |
| 3355 | 6 | Some Product 3355 | 18-04-2016 00:52:52 |
| 3355 | 6 | Some Product 3355 | 18-04-2016 00:52:52 |
Or define a custom table
var table = new ConsoleTable("one", "two", "three");
table.AddRow(1, 2, 3)
.AddRow("this line should be longer", "yes it is", "oh");
table.Write();
For further examples checkout c# console table
Your main tool would be
Console.WriteLine("{0,5} {1,10} {2,-10}", s1, s2, s3);
The ,5
and ,10
are width specifiers. Use a negative value to left-align.
Formatting is also possible:
Console.WriteLine("y = {0,12:#,##0.00}", y);
Or a Date with a width of 24 and custom formatting:
String.Format("Now = {0,24:dd HH:mm:ss}", DateTime.Now);
Edit, for C#6
With string interpolation you can now write
Console.WriteLine($"{s1,5} {s2,10} {s3,-10}");
Console.WriteLine($"y = {y,12:#,##0.00}");
You don't need to call String.Format()
explicitly anymore:
string s = $"Now = {DateTime.Now,24:dd HH:mm:ss}, y = {y,12:#,##0.00}" ;
Use \t to put in tabs to separate the columns