Type declaration in linq in lambda syntax

How to insert type declaration in lambda syntax?

Collects:

from DataRow row in dataTable.Rows select transformOneRow(row)

Not compiling:

dataTable.Rows.Select( r => transformOneRow(r))

with an error '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

I see that the syntax of the request allows a type; what makes the compiler happy.
How to insert type declaration in lambda syntax?

I have the following ways:

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.
+4
source share
1 answer

How to insert type declaration in lambda syntax?

The compiler converts the query syntax into method syntax. If you decompile your code, you will see that the emitted IL calls 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        

So, the equivalent would be, like you, a call Enumerable.Cast<DataRow>in your request prior to the offer Select.

+1
source

All Articles