简体   繁体   中英

C# What does a lambda that points to a new anonymous type mean?

I have used lambdas in the past with LINQ and making anonymous functions, but the following line has me confused.

(a,b) => new {a, b.PropertyA, b.PropertyB, b.PropertyC } 

What is going on here? It looks like anonymous method is pointing an anonymous type. This is being passed in as the "resultSelector" argument to a Join method.

Let's look at it in the larger context. We've got a table of customers and a table of orders, where each customer has an integer ID and each order has the ID of the customer who did the ordering. We want all the customers with the amounts of all their orders:

var results = customers.Join(
  orders,
  customer => customer.Id,
  order => order.CustomerId,
  (customer, order) => new {customer, order.Amount});

The compiler will translate that into:

IEnumerable<SomeAnonType<Customer, decimal>> results = 
  Enumerable.Join<Customer, Order, int, SomeAnonType<Customer, decimal>>(
    customers,
    orders,
    (Customer customer) => { return customer.Id; },
    (Order order) => { return order.CustomerId; },
    (Customer customer, Order order) => { return new {customer, order.Amount};} );

Join will enumerate all the customers and all the orders, fetching their ids based on the first two lambdas, and build a collection of (customer, order) pairs where the ids match. Then it will iterate over the collection of pairs and pass them to the third lambda to produce a sequence of objects of anonymous type.

Is that now clear? Or do you need more explanation of what is going on here?

Exercise : Suppose Order.CustomerId is of type int? , not int . Should that be an error? Or should C# figure that if Customer.Id is int and Order.CustomerId is int? then the user probably meant "treat the int as int? "? Suppose you did a join where the join keys were of type Giraffe and Turtle . Should type inference assume that you meant Animal , or should it give an error saying that it is unclear which type was intended? This was one of many subtle questions that we pondered when designing and implementing type inference in C# 3, and it only got harder when I added generic variance in C# 4! See if you can work it out.

The specified code represents a function taking two parameters and when invoked will create a new anonymous type with the specified properties.

So, this:

(a,b) represents the parameters.

and this:

new {a, b.PropertyA, b.PropertyB, b.PropertyC } 

is the code to be executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM