csharp 用于创建文本表的字符串构建器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 用于创建文本表的字符串构建器相关的知识,希望对你有一定的参考价值。

 public class TableStringBuilder<T>
{
    private readonly List<string> columnNames;
    private readonly List<Func<T, string>> stringFunctions;
    public TableStringBuilder()
    {
        columnNames = new List<string>();
        stringFunctions = new List<Func<T, string>>();
    }
    private static string padLeft(string s, char c, int length)
    {
        while (s.Length < length)
        {
            s = c + s;
        }
        return s;
    }
    public void addColumn(string columnName, Func<T, string> fieldFunction)
    {
        columnNames.Add(columnName);
        stringFunctions.Add((p) => fieldFunction.Invoke(p));

    }
    private int computeMaxWidth(int column, List<T> elements)
    {
        int n = columnNames[column].Length;
        var f = stringFunctions[column];
        foreach (var element in elements)
        {
            string s = f.Invoke(element);
            n = Math.Max(n, s.Length);
        }
        return n;
    }
    private List<int> computeColumnWidths(List<T> elements)
    {
        var columnWidths = new List<int>();
        for (int c = 0; c < columnNames.Count(); c++)
        {
            int maxWidth = computeMaxWidth(c, elements);
            columnWidths.Add(maxWidth);
        }
        return columnWidths;
    }
    public string createString(List<T> elements)
    {
        List<int> columnWidths = computeColumnWidths(elements);

        StringBuilder sb = new StringBuilder();
        for (int c = 0; c < columnNames.Count(); c++)
        {
            if (c > 0)
            {
                sb.Append("|");
            }
            var format = "{0" + "," + $"-{columnWidths[c]}" + "}";
            sb.AppendFormat(format, columnNames[c]);
        }
        sb.Append(Environment.NewLine);
        for (int c = 0; c < columnNames.Count(); c++)
        {
            if (c > 0)
            {
                sb.Append("+");
            }
            sb.Append(padLeft("", '-', columnWidths[c]));
        }
        sb.Append(Environment.NewLine);

        foreach (var element in elements)
        {
            for (int c = 0; c < columnNames.Count(); c++)
            {
                if (c > 0)
                {
                    sb.Append("|");
                }

                var f = stringFunctions[c];
                String s = f.Invoke(element);
                var format = "{0" + "," + $"-{columnWidths[c]}" + "}";
                sb.AppendFormat(format, s);
            }
            sb.Append(Environment.NewLine);
        }
        return sb.ToString();
    }
}

以上是关于csharp 用于创建文本表的字符串构建器的主要内容,如果未能解决你的问题,请参考以下文章

从 Impala 分区拼花表创建文本表

Tableau 去掉文本表中的abc字符

Tableau 去掉文本表中的abc字符

Tableau 去掉文本表中的abc字符

设置文本表 hsqldb Java

修剪文本表并将值存储为变量