LINQ Queries and Context

I have a little problem with the 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 happens is the variable "linq" differs depending on the value of the "parameter". When I try to go through "linq" with my foreach loop, I get an error when linq does not exist in the current context.

What is the best way to solve this problem?

+3
source share
2 answers

What you tried does not work, because the variable linqno longer works when you try to use it. You need to move the ad to the outside area.

: , var. :

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;
}

, :

var query = from a in db.table select a;
if (parameter != 1)
{
    query = query.Where(a => a.id == 1);
}
+9

, , , .

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.

linq , .

0

Source: https://habr.com/ru/post/1749095/


All Articles