Search code examples
ado.netsqldatareaderdatareader

How do i get the ordinal of a column in a DataReader


How can i find out if a column exists in a DataReader's results set?

i try:

int columnOrdinal = reader.GetOrdinal("LastName");
columnExists = (columnOrdinal < 0);

but GetOrdinal throws an exception if the column does not exist. My case is not exceptional. It's the opposite. It's...ceptional.


Note: Not related to my question but, the real reason i want to know if a column exists is because i want to get the ordinal position of a column, without throwing an exception if the column doesn't exist:

int columnOrdinal = reader.GetOrdinal("Lastname");

Note: Not related to my question but, the real reason i want to know if a column exists, because i want to know if the column contains null:

itIsNull = reader.IsDBNull(reader.GetOrdinal("Lastname"));

Unfortunately IsDBNull only takes an ordinal, and GetOrdinal throws an exception. So i'm left with:

if (ColumnExists(reader, "Lastname"))
{
   itIsNull = reader.IsDBNull(reader.GetOrdinal("Lastname"));
}
else
   itIsNull = false;

Note: Not related to my question but, the real reason i want to know if a column exists is because there will be times where the column will not be present in the results set, and i don't want to throw an exception processing database results, since it's not exceptional.


Solution

  • There is a limit to what you can do since the IDataReader doesn't expose much that helps. Using the loop as shown in the answer to a similar question

    Check for column name in a SqlDataReader object

    You could, with the first row you process, build a simple dictionary that is keyed by column name with ordinals as values (or a HashSet if you don't care about the ordinal values). Then you can just use columnDictionary.ContainsKey("LastName") as your test. You would only build the dictionary once, for the first row encountered, then all the subsequent rows would be fast.

    But to be honest, compared with database time, the time consumed by using as-is the solution in that other stackoverflow qeustion would probably be negligible.

    Edit: additional possibilities here: Checking to see if a column exists in a data reader