views:

2447

answers:

3

Hello there,

I have an interesting question. Imagine I have a lot of data changing in very fast intervals. I want to display that data as a table in console app. f.ex:

-------------------------------------------------------------------------
|    Column 1     |    Column 2     |    Column 3     |    Column 4     |
-------------------------------------------------------------------------
|                 |                 |                 |                 |
|                 |                 |                 |                 |
|                 |                 |                 |                 |
-------------------------------------------------------------------------

How to keep things fast and how to fix column widths ? I know how to do that in java, but I don't how it's done in C#.

+2  A: 
Martin Peck
+5  A: 

Use String.Format with alignment values.

For example:

String.Format("|{0,5}|{1,5}|{2,5}|{3,5}|", arg0, arg1, arg2, arg3);

To create one formatted row.

huusom
Wouldn't that print the same value four times?
Brian Rasmussen
Yeah, you should fix : String.Format("|{0,10}|{1,10}|{2,10}|{3,10}|", arg0, arg1, arg2, arg3);
Lukas Šalkauskas
+3  A: 

You could do something like the following:

static void Main(string[] args)
{
    Console.Clear();
    PrintLine();
    PrintRow("Column 1", "Column 2", "Column 3", "Column 4");
    PrintLine();
    PrintRow("", "", "", "");
    PrintRow("", "", "", "");
    PrintLine();
    Console.ReadLine();
}

static void PrintLine()
{
    Console.WriteLine(new string('-', 73));
}

static void PrintRow(string column1, string column2, string column3, string column4)
{
    Console.WriteLine(
        string.Format("|{0}|{1}|{2}|{3}|", 
            AlignCentre(column1, 17), 
            AlignCentre(column2, 17), 
            AlignCentre(column3, 17), 
            AlignCentre(column4, 17)));
}

static string AlignCentre(string text, int width)
{
    if (string.IsNullOrEmpty(text))
    {
        return new string(' ', width);
    }
    else
    {
        return text.PadRight(width - (width-text.Length)/2).PadLeft(width);
    }
}
Patrick McDonald
nice stuff, thanks :)
Lukas Šalkauskas
huuson's suggestion is less verbose (less code = less bugs) and does the same job
DonkeyMaster
huusom's solution has bugs, mine doesn't
Patrick McDonald