shikhar gilhotra wrote:
I also can't define var vv
globally since it is not allowed. What should I do?
Apparently, in my answer I've explained what you cannot do and why, see
Solution 2. I did not give you and idea on what to do. I'll fix this problem now.
Let's consider the very first Microsoft sample explaining the use of LINQ,
http://msdn.microsoft.com/en-us/library/bb397906.aspx[
^].
Here is that sample, written using
var
:
static void Main(string[] args) {
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
var numQuery =
from num in numbers
where (num % 2) == 0
select num;
foreach (int num in numQuery)
Console.Write("{0,1} ", num);
}
Now, you want to make an
if
branch with different queries. You correctly explain why you cannot do it with
var
. Let's be logical. It means that if you want to use the similar code logic and structure, you will need to exclude
var
by using explicit type. Here is how:
static void Sample(bool condition) {
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
IEnumerable<int> numQuery;
if (condition)
numQuery =
from num in numbers
where (num % 2) == 0
select num;
else
numQuery =
from num in numbers
where (num > 4)
select num;
foreach (int num in numQuery)
Console.Write("{0,1} ", num);
}
It is important to understand, that the
run-time type is different from the
compile-time type declared in the code sample shown above. You can use the nearest common base type which is assigned-compatible with the operand of your
foreach
container.
The problem is reduced to the problem of selection of appropriate query type for the explicit declaration. The rules are very well explained here:
http://msdn.microsoft.com/en-us/library/bb397924.aspx[
^].
Good luck,
—SA