views:

451

answers:

5

I need to declare the query variable outside the switch statement that way I would only have one variable that would handle different result of the LINQ Query. Please see the code below. Problem here is that I cannot infer a variable without initializing it

var query;

Switch(filter)
{

case 1:
    var query = from c in Customers 
                where c.Type equals == 'ABC'
                select c; 
     break;
case 2:
    var query = from c in Customers
                where c.Type equals == 'CDE'
                select c;
     break;
 }

foreach(var custrow in query)
{
    //Do Logic
}

}
+4  A: 

You probably want IEnumerable<Customer> or IQueryable<Customer> instead of var.

ScottS
+2  A: 

No because they have to be in initialized at the same time as they are declared, the complier doesn't know what type to assign to the variable.

I think you would want something like.

IQueryable<Customers> query;

that is assuming that the query returns a IQueryable of Customers.

overall design something like this may be better.

IQueryable<Customers> query;

Switch(filter)
{

case 1:
    query = Customers.Where(c => c.Type == "ABC");
    break;
case 2:
    query = Customers.Where(c => c.Type == "CDE");
    break;
}

foreach(var custrow in query)
{
    //Do Logic
}
Nathan W
A: 

Hate to point this out but, this:

var query;

Won't compile. Inferred variables need to be assigned immediately.

I agree with the above answers. You would need to declare it as IEnumerable<Customer> or IQueryable<Customer> for it to work.

Jon Limjap
A: 

Besides agreeing with Scott, Nathan & Jon, I would like to point out that maybe it would be a good idea to refactor this a little bit. It is always a good practice to keep functions doing only one thing:

private IEnumerable<Customer> FetchCustomers(FilterType filter)
{
    switch (filter)
    {
       // Switch logic comes here
    }
}

private void ProcessCustomers(IEnumerable<Customer> customers)
{
    foreach (var customer in customers)
    {
       // Process logic comes here
    }
}

private void FetchAndProcessCustomers(FilterType filter)
{
    ProcessCustomers(FetchCustomers(filter));
}

Now it looks much nicer and simpler, and as a bonus, your problem regarding inferred variables just gone away!

DrJokepu
A: 

Thanks all for the answers and code provided. It helped a lot

Roy Astro