Question

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!!!?!!!

Was it helpful?

Solution

Instead of:

var result;

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

IEnumerable<Job> result;

OTHER TIPS

You can only use var if the compiler can know exactly which type to use (or how to define a new type for you).

In your case you can either define it with the type say

List<Job> result;

or call the constructor to return an instance:

var result = new List<Job>;

(of course your query will return an IEnumarable instance instead of a List, I just used List as an example because you can't instantiate an enumeration.)

Just as a note, as your if statements determine the filters for the query rather than the query itself, you might want to build up a SimpleExpression there and run the query afterwards. For example.

var whereCLause;

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

List<Job> results = db.Jobs.All.Where(whereClause);
foreach(Job record in results)
{
  ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top