[c#] Can you get the column names from a SqlDataReader?

3 Answers

There is a GetName function on the SqlDataReader which accepts the column index and returns the name of the column.

Conversely, there is a GetOrdinal which takes in a column name and returns the column index.


After connecting to the database, can I get the name of all the columns that were returned in my SqlDataReader?

I use the GetSchemaTable method, which is exposed via the IDataReader interface.

Use an extension method:

    public static List<string> ColumnList(this IDataReader dataReader)
        var columns = new List<string>();
        for (int i = 0; i < dataReader.FieldCount; i++)
        return columns;

Already mentioned. Just a LINQ answer:

var columns = reader.GetSchemaTable().Rows
                                     .Select(r => (string)r["ColumnName"])


var columns = Enumerable.Range(0, reader.FieldCount)

The second one is cleaner and much faster. Even if you cache GetSchemaTable in the first approach, the querying is going to be very slow.