I have a slight issue with some code I’m writing
if(parameter == 1)
{
var linq = from a in db.table select a;
}
else
{
var linq = from a in db.table where a.id = 1 select a;
}
foreach(var b in linq)
{
...
}
So basically what’s going on is that the variable “linq” is different depending on the value of “parameter”. When I try to loop through “linq” with my foreach loop, I get an error about how linq doesn’t exist in the current context.
What is the best way to work around this type of issue?
What you tried doesn’t work because the variable
linqis already out of scope when you try to use it. You need to move the declaration to the outer scope.To answer your question in a general way first: if you need to declare a variable before you assign to it, you can’t use
var. You need to declare the type explicitly:In your particular example though you can simplify things: