In the simplified code below,
if(city == "New York City")
{
var MyObject = from x in MyEFTable
where x.CostOfLiving == "VERY HIGH"
select x.*;
}
else
{
var MyObject = from x in MyEFTable
where x.CostOfLiving == "MODERATE"
select x.*;
}
foreach (var item in MyObject)
{
Console.WriteLine("<item's details>");
}
The variable MyObject is not accessible outside conditional block. How can I iterate outside the if..else ?
Let's clarify your confusing question. The problem is that you have two local variables, each of which has the same "unspeakable" type -- a sequence of anonymous type.
I would change your specific code like this:
However, if you still need to maintain the structure of the code as it is for some reason, you can do it like this:
This is a variation on a trick called "cast by example" where you give an example of an anonymous type to a generic method. Method type inference then figures out what the return type is, and uses that as the type of the implicitly typed local. At runtime, it does nothing but create a useless object that then gets discarded quickly.
you'll have to define the MyObject as a var before the condition:
This will assign a schema to the MyObject variable.
Now you can proceed with your condition as:
If you're using a named type, just declare a variable with that type before the
if
, but then the question would be trivial.So I assume you're selecting an anonymous type, so you can't explicitly declare a variable with that type.
Cast by example would work here. But that doesn't feel like a good solution. Probably creating a named type is a better idea.
Or in your specific example one could project only after the conditional:
Or:
Or even just:
Which one is appropriate depends on how you simplified your question.
You will need to declare the variable outside of the scope of the if statement in order to use it in the foreach loop.
If the variable is declared but not initialized outside the if statement it can't be typed implicitly because the compiler won't have an expression to determine the type from.
If it's only going to be used in the foreach loop you can declare it as an IEnumerable.
Try this: