You are correct that exceptions should not be used for normal program flow.
The GetOrdinal method GetOrdinal designed for situations where you know which fields you are receiving, and if there is no field, this is an error that should lead to an exception.
If you do not know which fields you will get as a result, you should avoid the GetOrdinal method. Instead, you can get all the names and their index into a dictionary, which you can use as a replacement for the GetOrdinal method:
public static Dictionary<string, int> GetAllNames(this IDataRecord record) { var result = new Dictionary<string, int>(); for (int i = 0; i < record.FieldCount; i++) { result.Add(record.GetName(i), i); } return result; }
You can use the ContainsKey method to check if a name exists in the dictionary, or the TryGetValue method to check if this name exists and index it in one operation.
The GetOrdinal method first searches for a sensitive case, and if that fails, it searches the case without checking. This is not provided by the dictionary, so if you want this exact behavior, you prefer to store the names in an array and write a method to scroll through them when you want to find the index.
Guffa
source share