What is the scope of a lambda variable in C#?

2019-01-22 10:53发布

I'm confused about the scope of the lambda variable, take for instance the following

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
    };

In line 1 I have declare a lambda variable 'o' which means I cannot declare it again in line 2 (or at least the compiler complains if I try to) But it doesn't complain about line 3 even though 'o1' already exists??

What is the scope of a lambda variable?

标签: c# lambda scope
8条回答
唯我独甜
2楼-- · 2019-01-22 11:16

You cannot use the same variable name in two scopes if one of the scopes contains the other.

In your question, o is introduced in the outer scope, so it cannot be used again in the second Where() or in Max(), because these scopes are contained in the outer one.

On the other hand, you can use o1 in both inner scopes because one does not contain the other, so there is no ambiguity there.

查看更多
干净又极端
3楼-- · 2019-01-22 11:17

I try picture it like this as per your code...

.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
    )

Rather crude way of explaining but your brackets determine the scope. Your 2nd o1 isn't nested inside the second where, other wise you'd have the same problem

//outermost where

((BEGIN-o

//inner where

(BEGIN-o1 END-o1)

//max

(BEGIN-o1 END-o1)

END-o))
查看更多
登录 后发表回答