I have following code snippet in c#
static void Main()
{
var numbers = new[] { 1, 2, 3, 4, 5, 6 };
var ngt5 = numbers.Where(n => n > 5);
var n = ngt5.First().ToString();
Console.WriteLine(n, numbers);
}
When I am compiling the above code I am getting following error
A local variable named ‘n’ cannot be declared in this scope
Your problem is here:
To understand why this is a problem, consider the following code:
The expression
n % 2 == 0above is ambiguous: whichnare we talking about? If we’re talking about the outern, thenn % 2 == 0is always true sincenis just 1000 (and thereforeevenswill comprise all numbers from 1 to 1000). On the other hand, if we’re talking about the innern, thenn % 2 == 0will only hold true for even values ofn(andevenswill be 2, 4, 6, … 1000).The important point to realize is that variables declared outside the lambda are accessible from within the lambda’s scope.
This is why the ambiguity exists, and why it is therefore not allowed.
The solution is simply to pick a different variable name for your lambda; e.g.: