GetOrdinal
Int32ordinal
= DataReader.GetOrdinal(StringcolumnName
);
Retrieves the zero-based ordinal for the column with the specific
name. This is useful for two reasons. First of all, many
DataReader
methods require the use of column
ordinals, not field names. Second, access via a column ordinal is
likely to perform faster. In fact, when you use a column name,
ADO.NET performs a hashtable lookup behind the scenes to determine
the correct column ordinal. Using GetOrdinal( )
,
you can perform this lookup once, rather than every time you need to
access a field.
The following code shows a simple example of how you might access a column using the column ordinal, even if you only know its column name:
// Perform the ordinal lookups. int colID = r.GetOrdinal("CustomerID"); int colFirstName = r.GetOrdinal("FirstName"); int colSecondName = r.GetOrdinal("SecondName"); while (r.Read()) { // Use the ordinals far faster column value access. Console.WriteLine(r[colID].ToString()); Console.WriteLine(r[colFirstName].ToString() + " " + r[colSecondName].ToString()); Console.WriteLine(); }