如何将类型声明插入lambda语法?
编译:
from DataRow row in dataTable.Rows select transformOneRow(row)
不编译:
dataTable.Rows.Select( r => transformOneRow(r))
有错误
'System.Data.DataRowCollection' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'System.Data.DataRowCollection' could be found
我看到查询语法允许一个类型;这让编译器感到高兴 如何将类型声明插入lambda语法?
我的方式是:
dataTable.AsEnumerable().Select(r => transformOneRow(r));
dataTable.Rows.Cast<DataRow>().Select(r => transformOneRow(r));
dataTable.Rows.OfType<DataRow>().Select(r => transformOneRow(r)); // Also does filtering on type.
答案 0 :(得分:1)
如何将类型声明插入lambda语法?
编译器会将查询语法转换为方法语法。如果您对代码进行反编译,您将看到发出的IL调用Enumerable.Cast<T>
:
IL_0000: nop
IL_0001: newobj System.Data.DataTable..ctor
IL_0006: stloc.0 // dataTable
IL_0007: ldloc.0 // dataTable
IL_0008: callvirt System.Data.DataTable.get_Rows
IL_000D: call System.Linq.Enumerable.Cast <--- This
IL_0012: ldsfld UserQuery+<>c.<>9__0_0
IL_0017: dup
IL_0018: brtrue.s IL_0031
IL_001A: pop
IL_001B: ldsfld UserQuery+<>c.<>9
IL_0020: ldftn UserQuery+<>c.<Main>b__0_0
IL_0026: newobj System.Func<System.Data.DataRow,System.Data.DataRow>..ctor
IL_002B: dup
IL_002C: stsfld UserQuery+<>c.<>9__0_0
IL_0031: call System.Linq.Enumerable.Select
IL_0036: stloc.1 // result
IL_0037: ret
因此,正如您所做的那样,在Enumerable.Cast<DataRow>
子句之前,在查询中调用Select
。