Search code examples
c#console.writeline

In C#, how do I use Console.WriteLine method to write ALL columns from my SqlCommand


I'm new to C# but have managed to piece together an SQLCommand query. However , I can't for the life of me figure out how to get it to display all columns. The below code is what i have currently (it successfully shows the first 5 columns):

Console.WriteLine(String.Format("{0} \t | {1} \t | {2} \t | {3} \t| {4} \t",
    reader[0], reader[1], reader[2], reader[3], reader[4]));

What is the simplest way to show ALL columns without having to list each one like I did above? Also, is there a way to specifically name the columns that i want to display? for example, the below successfully shows the "company" column but I cant figure out how to do multiple columns specifically. What if i wanted to show "company" and "FiscalYear"?:

Console.WriteLine(reader["Company"].ToString());

I researched this for about 2 hours but was unable to come up with a solution. thank you very much for your help!


Solution

  • You can use a StringBuilder to create the text in a loop

    var sb = new StringBuilder();
    for (int i = 0; i < reader.FieldCount; i++) {
        sb.Append($"{reader[i]} \t |");
    }
    sb.Length -= 4; // Remove the last " \t |".
    Console.WriteLine(sb);
    

    sb.Append(something) is more efficient than s = s + something, because string concatenations always create a new string object and copy the old string to the new one before appending something. Whereas the StringBuilder works with a buffer and can append several times until the buffer is full and must be resized.

    The $ stands for string interpolation. These two lines are equivalent:

    String.Format("{0}, {1}, {2}", a, b, c)
    $"{a}, {b}, {c}"