tags:

views:

73

answers:

2

Hello SO,

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?

+9  A: 

What you tried doesn't work because the variable linq is 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:

IQueryable<Something> linq;
if(parameter == 1)
{
    linq = from a in db.table select a;
}
else
{
    linq = from a in db.table where a.id == 1 select a;
}

In your particular example though you can simplify things:

var query = from a in db.table select a;
if (parameter != 1)
{
    query = query.Where(a => a.id == 1);
}
Mark Byers
+1 but based on the OP's sample I think it should be `if (parameter != 1)` (for the 2nd code sample)
Ahmad Mageed
Oh right, you can query linq results (which is such a fundamentally important feature of linq that I'm just starting to appreciate). This is very helpful, thanks!
Soo
@Ahmad Magged: +1 Thanks. Well spotted!
Mark Byers
@Soo: I'm querying the *query*, which gives a new *query*. There are no results until you ask for them, for example by writing `foreach (var result in query)`.
Mark Byers
@Mark, Thank you for that correction, It's valuable for me to pick up the correct terminology as I pick these concepts up. :)
Soo
`var query = db.table;`
SLaks
@SLaks: Are you sure? `db.table` probably has type `Table<Something>` which I think would cause the assignment further down to fail with a type error (`cannot convert from IQueryable<T> to Table<T>`).
Mark Byers
@Mark: You're right; you can't use `var` there.
SLaks
A: 

I dunno if this is the best way but, assuming you're returning the same table.

var linq  = from a in db.table where a.id = 1 select a;

if(parameter == 1)
{
 linq = from a in db.table select a;
}

//foreach.

You can reconstruct your linq query and not pay a big penalty, since you haven't actually executed it.

Alan