如何理解这个lambda表达式?

时间:2014-11-09 18:24:31

标签: c# linq

我是C#新手。有人可以帮我理解这个C#lambda表达式吗?

var projs = allCustomers.SelectMany(osd => osd.phoneNumbers,
                                   (osd, osv) => new { customer= osd, phoneNumber= osv });

感谢/下摆

1 个答案:

答案 0 :(得分:9)

您正在使用SelectMany的{​​{3}}。

public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(
      this IEnumerable<TSource> source,
      Func<TSource, IEnumerable<TCollection>> collectionSelector,
      Func<TSource, TCollection, TResult> resultSelector
)

有三个参数:

source :
Type: System.Collections.Generic.IEnumerable<TSource>
A sequence of values to project.

collectionSelector
Type: System.Func<TSource, IEnumerable<TCollection>>
A transform function to apply to each element of the input sequence.

resultSelector
Type: System.Func<TSource, TCollection, TResult>
A transform function to apply to each element of the intermediate sequence.

在您的情况下,sourceallCustomerscollectionSelector是表达式:

osd => osd.phoneNumber 

resultSelector是:

(osd, osv) => new { customer= osd, phoneNumber= osv }

此处第一个表达式表示每个customer并返回phoneNumbers。在第二个表达式中,osd的类型为customer,{{ 1}}是osv,结果是匿名类型。它接收每个客户和电话号码,并使用这些值创建匿名类型。

以下是此查询执行操作的示例:

phoneNumber

结果将是:

Customer - Phone Numbers
------------------------
John      1234567,2331212,1122334
Jack      1456771,9485323
Juliet    2401232