开发者

How to format a list of some classes into a nice ASCII table in C#?

Have a LINQ result, need to format it in plain text nicely to send by email.

For example each record contains "ProductName", "SalesAmount", "Taxes" And product names could be strings different length for different records.

Need to format a list of such records as plaintext table. Using "----------" as horizontal line and "|" as vertical line.

As you don't know the max size of product name you don't know the size of vertical line in characters for it. Suppose need to find the maximum product name length and depending on开发者_如何学JAVA it calculate amount of "-" characters needed. But is there anything that can auto format?

Assuming that font is mono-spaced.

What is the best way to do it?

Thanks.


What you may be looking for is the alignment parameter in a format string. I.e.:

string s = String.Format("{0,-20}{1,-20}{2,-20})", "one", "two", "three");

will render in three equal columns, left-aligned (right-aligned when you remove the minus sign) on 20 characters each. Use this to make nice columns in text-only with your data.

After your edit:

// loop through your data and find the largest common size (note: you can use LINQ)
int maxCol1 = 0;
int maxCol2 = 0;
foreach(item in yourData)
{
    maxCol1 = item.Col1 > maxCol1 ? item.Col1 : maxCol1;
    maxCol2 = item.Col2 > maxCol2 ? item.Col2 : maxCol2;
}

// create formatting strings, add all sizes:
string line = new String('-', 2 + maxCol1 + maxCol2 + nr of columns ...);
string formatString = String.Format(
      "|{{0,-{0}}}|{{1,-{1}}}|{{2,-{2}}}|)", 
      maxCol1,maxCol2 ...);

// create your text-only mail neatly formatted
yourStringWriter.WriteLine(line);
foreach(item in yourData)
{
    yourStringWriter.WriteLine(String.Format(formatString, item.Col1, item.Col2);
    yourStringWriter.WriteLine(line);
}

The above will output the following (replace the notorious Col1, Col2 with your properties, like Name, Address etc):

----------------------
|one   |two   |three |
|four  |five  |six   |
|seven |eight |nine  |
----------------------


There isn't a reliable way to do this (if you're looking for a nice square table) in plain-text mail, because you can't assume much about the way email clients use tabs, and you can't line things up with spaces because you don't know what font people will be using.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜