我对lambda变量的范围感到困惑,例如以下内容
var query =
from customer in clist
from order in olist
.Where(o => o.CustomerID == customer.CustomerID && o.OrderDate == // line 1
olist.Where(o1 => o1.CustomerID == customer.CustomerID) // line 2
.Max(o1 => o1.OrderDate) // line 3
)
select new {
customer.CustomerID,
customer.Name,
customer.Address,
order.Product,
order.OrderDate
};
Run Code Online (Sandbox Code Playgroud)
在第1行中,我声明了一个lambda变量'o',这意味着我不能在第2行再次声明它(或者至少编译器在我尝试时会抱怨)但是即使'o1'已经存在,它也不会抱怨第3行??
lambda变量的范围是什么?
为什么我的参数x表现得如此不规律?
x因为它是在"子"范围内定义的.例1:
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
var result = list.Where(x => x < 3);
Console.Write(result.ElementAt(x));
Run Code Online (Sandbox Code Playgroud)
创建此编译时错误:
当前上下文中不存在名称"x"
我期待的.
例2:
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
var result = list.Where(x => x < 3);
int x = 1;
Console.Write(result.ElementAt(x));
Run Code Online (Sandbox Code Playgroud)
产生这个编译时错误:
名为'x'的局部变量不能在此范围内声明,因为它会给'x'赋予不同的含义,'x'已在'子'范围内用于表示其他内容
我理解在这个问题中回答的范围,C#在foreach中重用变量是否有原因?.然而,这是我以前从未见过的.另外,它回答了这个问题,C#中lambda变量的范围是什么?,不完整或错误.
例3:
List<int> list = new …Run Code Online (Sandbox Code Playgroud)