title: Cast Queried Results To Tuple
body: <p>I am attempting to create a function that will take the results of a database query and put them into a generic tuple. I have code that successfully works when querying Sql Server or Sybase databases but I'm having difficulty making it work with an OleDb connection to an excel document.</p>
  <p>Usage Example:</p>
  <pre><code>var myTuple = excelConnection.ExecuteTuple&lt;(string, string, int)&gt;(&quot;SELECT * FROM [Sheet1$]&quot;, new OleDbParameter[0])
  </code></pre>
  <p>Here is the code I'm using for Sql Server and Sybase to convert the results just updated to use OleDb:</p>
  <pre><code>public T ExecuteValue&lt;T&gt;(string sqlStatement, IEnumerable&lt;OleDbParameter&gt; parameters) where T : ITuple
  {
      using var connection = new OleDbConnection(connectionString);
      using var command = new OleDbCommand(sqlStatement, connection);
      command.Parameters.AddRange(parameters);
      connection.Open();
      var reader = command.ExecuteReader();
  
      T results = default;
      int tupleFields = results.Length;
  
      // Read the results into the tuple
      reader.Read();
  
      for (int i = 0; i &lt; tupleFields; ++i)
      {
          object tupleObject = results;
  
          //Set the values of the Tuple
          var setValue = reader.GetValue(i) == DBNull.Value ? default : reader.GetValue(i);
  
          //This call fails to set the value.
          //If the tuple doesn't match the exact type its stored in excel as.
          //So all numeric values must be cast to double.
          results.GetType().GetField($&quot;Item{i + 1}&quot;).SetValue(tupleObject, setValue);
  
          results = (T)tupleObject;
      }
  
      return results;
  }
  </code></pre>
  <p>When working with individual values I am able to do this:</p>
  <pre><code>result = reader.GetValue(0) == DBNull.Value ? default :(T)Convert.ChangeType(reader.GetValue(0), typeof(T));
  </code></pre>
  <p>But I haven't been able to figure out how to use the type of that individual element of the tuple in a cast like is being done with the individual values.</p>