我需要方法在控制台应用程序中打印List作为表格并以方便的格式预览,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
Hen*_*man 40
你的主要工具是
Console.WriteLine("{0,5} {1,10} {2,-10}", s1, s2, s3);
Run Code Online (Sandbox Code Playgroud)
的,5和,10是宽度说明.使用负值进行左对齐.
格式化也是可能的:
Console.WriteLine("y = {0,12:#,##0.00}", y);
Run Code Online (Sandbox Code Playgroud)
或者宽度为24的日期和自定义格式:
String.Format("Now = {0,24:dd HH:mm:ss}", DateTime.Now);
Run Code Online (Sandbox Code Playgroud)
使用字符串插值,您现在也可以编写
Console.WriteLine($"{s1,5} {s2,10} {s3,-10}");
Console.WriteLine($"y = {y,12:#,##0.00}");
String.Format($"Now = {DateTime.Now,24:dd HH:mm:ss}" );
Run Code Online (Sandbox Code Playgroud)
您无需String.Format()明确调用:
string s = $"Now = {DateTime.Now,24:dd HH:mm:ss}" + " " + $"y = {y,12:#,##0.00}" ;
Run Code Online (Sandbox Code Playgroud)
Nik*_*tov 24
最简单的方法是使用现有的库
Install-Package ConsoleTables
Run Code Online (Sandbox Code Playgroud)
然后你可以这样定义你的表:
ConsoleTable.From<Order>(orders).Write();
Run Code Online (Sandbox Code Playgroud)
它会给出这个输出
| 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 |
Run Code Online (Sandbox Code Playgroud)
或者定义自定义表
var table = new ConsoleTable("one", "two", "three");
table.AddRow(1, 2, 3)
.AddRow("this line should be longer", "yes it is", "oh");
table.Write();
Run Code Online (Sandbox Code Playgroud)
有关更多示例,请检查c#console table