开发者

Queryable variable cannot be found in the context

if(){...}
else{...}
            if ( query.Count > 0 ){...}

The displayed above is a skeleton similar to the one t开发者_JS百科hat I use. In the first if-then-else sequence I initialize a query variable (used in LINQ) called query and then check it at the next if -statement. Still the environment says that query is not presented in the current context. If the code from the if-then statement is used alone - then no problems are observed. It seems to me that the problem is with the initialization of the variable. Do you have any other suggestions?

If you have an idea how to initialize with null value a variable that is to be queried with link - I would be glad to hear this, too. Thank you!


Declare the variable before the if-else:

//replace var with the actual type, of course
var query;
if(){...}
else{...}

if (query.Count > 0){...}


The problem is that the scope of the "query" variable needs to be larger than the scope in which you've defined "query".

But since you've used var, you can't declare "query" until there's enough information for the compiler to choose the type.

To resolve, simply declare the type of the variable in the desired scope (don't use var).

IEnumerable<Customer> query = null;

if ()
{
  query = ...
}
else
{
  query = ...
}

if (query.Any())

Nothing in Linq depends on the use of the var keyword. Learn more about var here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜