Question

I get query result from SQL Server with dynamic number of columns with variable column names. How can I transform the result from datareader into generic list List ?

 public ? getItems(string orderId)
    {

        SqlConnection sqlConn = new SqlConnection(conn);
        SqlCommand command = new SqlCommand();
        SqlDataReader reader;
        try
        {
            sqlConn.Open();
            command.Connection = sqlConn;
            command.CommandText = "usp_get_orders";
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@Id", orderId)));

            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {

                ?
            }

            reader.Close();
        }
        catch (Exception exp)
        {

        }
        finally
        {

            command.Dispose();
            command1.Dispose();
            sqlConn.Close();
            sqlConn.Dispose();
        }

        return ?;
    }
Was it helpful?

Solution

If you resulting object is completely dynamic you could use a dictionary instead of a strongly typed object. Or, if you want at least an object, go with dynamic objects. Either use the dynamic keyword and a List<dynamic> or use DynamicObject. The difference to a dictionary is not that big though...

Something like this could do it:

SqlDataReader reader = command.ExecuteReader();
var listOfValues = new Dictionary<string, object>();
while (reader.Read())
{
   for(int i = 0; i <reader.FieldCount;i++)
   {
      listOfValues.Add(reader.GetName(i), reader.GetValue(i));
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top