Search code examples
c#dynamicvarsimple.data

Best practice for "var" (algorithm help)


I'm working with Simple.data, and the answer is not in the technology aforementioned but helps bring the point across. So ignore the syntax etc.

I am querying a database with a simple query; but based on a set of conditions, the query will change.

So for example: (very simplistic, probably 5-10 conditions)

     var result;

     if(LoggedAtSelected)
     {
      // Condition 1 - Calls Logged after a certain date
      result = db.Jobs.FindAll(db.Jobs.Logged_At >= startDate);
     }
     else 
     {
      // Condition 2 - Calls Closed after a certain date
      result = db.Jobs.FindAll(db.Jobs.Closed_At >= startDate && dd.Jobs.Closed_At <= endDate);
     }

     foreach(var JobRecord in result)
     {
     }

This is the ideal code above, but sadly this is not possible given the dynamic binding and variable nature of var. What is the best practice for this kind of situation? My only idea is to write a "var result = condition..." for every condition, and in the if..else if..else, to assign it to a global variable after converting it to that type; and then using it in the "foreach". Sounds a lot of work. Any ideas? Or is that it!!!?!!!


Solution

  • Instead of:

    var result;
    

    Use the actual type returned by db.Jobs.FindAll:

    IEnumerable<Job> result;