您可以使用填充来正确对齐输出。
找出你想要的每一列的宽度,然后相应地填充字符串:
var value = "Sample";
//Desired length
var length = 20;
//Trim strings longer than the desired length
value = (value.Length > length) ? $"{value.Substring(0,20)}..." : value;
//Pad to always have the same length
var paddedValue = value.PadRight(length, ' ');
在上面的示例中,paddedValue 将包含一个以 Sample 开头的字符串和 14 个额外的空格。
您可以阅读有关字符串填充的更多信息here。
这是一个简单的示例,但您应该清楚,您可以将其封装到可重用的函数/类中。
这是一个使用数组来说明的示例实现。您可以创建一个负责修剪/填充字符串的函数:
private static string GetFormattedValue(string value, int maxLength)
{
//Trim strings longer than the desired length
var output = (value.Length > maxLength) ? $"{value.Substring(0, 20)}..." : value;
//Pad to always have the same length
var paddedValue = output.PadRight(maxLength, ' ');
return paddedValue;
}
以下是一些示例定义和数据:
var lengths = new[] { 20, 30, 10 };
var headers = new[] { "Title", "Description Header that is also too long", "Quantity" };
var values = new[] {"Small text", "Super long text that will not fit", "15" };
使用 Linq 为 标头和值生成字符串(标头也可能太长!):
var headerString = string.Join("|", headers.Select((h, i) => GetFormattedValue(h, lengths[i])));
Console.WriteLine(headerString);
var valueString = string.Join("|", values.Select((v, i) => GetFormattedValue(v, lengths[i])));
Console.WriteLine(valueString);
输出: