.NET SqlDataReader Item[] vs. GetString(GetOrdinal())?

前端 未结 5 1227
感情败类
感情败类 2020-12-18 22:28

Using the SqlDataReader class, what, if any, are the functional differences between:

(string) dataReader[\"MyFieldName\"];

and

5条回答
  •  别那么骄傲
    2020-12-18 22:48

    Casting issues aside, for the singular call, there are none. The indexer will make a call to DbDataReader.GetOrdinal and then call the appropriate Get method to get the value (note that it's faster to call the Get methods using an ordinal than it is to use the indexer with the field name).

    However, this will incur a lookup of the ordinal every time. If you are iterating through a number of records in a forward-only, read-only way (which is exactly what DbDataReader instances are meant to do), then you can reduce the overhead of this lookup by doing it just once.

    You could do so like this:

    // Move to the first record.  If no records, get out.
    if (!dataReader.Read()) return;
    
    // Before the loop.  Can do this for any other fields being
    // accessed in the loop as well.
    int myFieldNameOrdinal = dataReader.GetOrdinal("MyFieldName");
    
    // Process the records.  Remember, already on the first record, so
    // use do/while here.
    do
    {
        // Do something with your field.
        Console.WriteLine(dataReader.GetString(myFieldNameOrdinal));
    } while (dataReader.Read());
    

提交回复
热议问题