27

I need Method to print List as table in console application and preview in convenient format like this:

Pom_No          Item_Code          ordered_qty                      received_qty

1011            Item_Code1         ordered_qty1                    received_qty1 

1011            Item_Code2         ordered_qty2                    received_qty2

1011            Item_Code3         ordered_qty3                    received_qty3

1012            Item_Code1         ordered_qty1                    received_qty1 

1012            Item_Code2         ordered_qty2                    received_qty2

1012            Item_Code3         ordered_qty3                    received_qty3
Anas Jaber
  • 583
  • 1
  • 7
  • 20

3 Answers3

51

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}" ;
H H
  • 263,252
  • 30
  • 330
  • 514
38

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

Nikita Ignatov
  • 6,872
  • 2
  • 34
  • 34
2

Use \t to put in tabs to separate the columns

Gwyn Howell
  • 5,365
  • 2
  • 31
  • 48