9

I have the following code and i want to loop through all the fields in the result of this query and populate the dictionary called field.

Given a datareader is this possible?

            OracleCommand command = connection.CreateCommand();
            string sql = "Select * from MYTABLE where ID = " + id;
            command.CommandText = sql;

            Dictionary<string, string> fields = new Dictionary<string, string>();
            OracleDataReader reader = command.ExecuteReader();
leora
  • 188,729
  • 360
  • 878
  • 1,366

2 Answers2

19

You should be able to do something like this:

Dictionary<string, string> fields = new Dictionary<string, string>();
OracleDataReader reader = command.ExecuteReader();

if( reader.HasRows )
{
    for( int index = 0; index < reader.FieldCount; index ++ )
    {
        fields[ reader.GetName( index ) ] = reader.GetString( index );
    }    
}
MikeWyatt
  • 7,842
  • 10
  • 50
  • 71
  • If you have data thats not strings only, you should swap the inside of the for-loop with this: fields[reader.GetName(index)] = reader.GetValue(index).ToString(); – hansmei Oct 16 '20 at 17:11
4

GetSchemaTable will return a lot of information about the columns, including their name but also size, type, etc.

I presume you want the key of the dictionary to be the column name, and the value to be the row value. If so, this should work:

var dict = reader.GetSchemaTable().Rows.OfType<DataRow>().Select(
    r => r["ColumnName"].ToString()
).ToDictionary(
    cn => cn,
    cn => reader[cn].ToString()
);

You could also use GetValues() to get the number of columns, and call GetName(int) for each.

Rex M
  • 142,167
  • 33
  • 283
  • 313