Note that there are some explanatory texts on larger screens.

plurals
  1. POUse of NULL local variable for List<dynamic> in C#
    text
    copied!<p>The best solution I could find (anywhere) to get results from an SQL Query into a local variable was to use a NULL <code>List&lt;dynamic&gt;</code> or <code>IEnumerable&lt;dynamic&gt;</code> variable declaration.</p> <p>Creating the variable by doing something like:</p> <pre><code>@{ IEnumerable&lt;dynamic&gt; myVariable = null; } </code></pre> <p>The variable can then get a value from a database query like:</p> <pre><code>@{ try { Database db = Database.Open("name"); // name of connectionString configured in web.config string myQuery = "EXEC dbo.Get_Results @Param1=@0, @Param2=@1"; myVariable = db.Query(myQuery, @Param1, @Param2); db.Close(); db.Dispose(); } catch (Exception ex) { // Do something } </code></pre> <p>Which allows me to do something like the following:</p> <pre><code>@if(myVariable != null) { foreach (var row in myVariable) { // Do something } } </code></pre> <p>This is working perfectly, but what I am still curious is how to do the same using <code>List&lt;dynamic&gt;</code>, as an alternative to using <code>IEnumerable&lt;dynamic&gt;</code> the way I am using it.</p> <p><strong>What is the <code>List&lt;dynamic&gt;</code> equivalent solution that I am using for <code>IEnumerable&lt;dynamic&gt;</code>?</strong></p> <p>I know my question itself is very simple, but it took me a long time to get past trying to solve <em>can't implicitly convert</em> errors when I tried to create a Class that could receive the results from <code>db.Query(commandText)</code> into a pre-declared variable. So I thought I should provide more detail in case this helps someone else trying to figure out the same or similar. I found my solution on the <code>IEnumerable&lt;dynamic&gt;</code> in unrelated topic which opened my eyes to much simpler solution to problem I was trying to solve.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload