tags:

views:

53

answers:

2

i hope i'm just doing something wrong here. Ideally i'm trying to open the connection, open a transaction execute a ton of prebuilt sqlstatements (with parameters) against this connection then close the connection. ideally all in the same batch.

It's easy enough to wrap this all in a for loop, however i'd like to use the forEach function of the list generic to set the connection as it'll probably be faster than my implementation of calling List.Item(i) in the loop but i get some strange errors.

 Dim sqlStatements As List(Of SqlCommand) = New List(Of SqlCommand)        
 Dim conn As SqlClient.SqlConnection = New SqlConnection("...")



 sqlStatements.Item(0).Connection = conn 
 'Works

sqlStatements.ForEach(Function(ByRef cmd As SqlCommand) cmd.Connection = conn)
 'ERROR: Operator '=' is not defined for types 
       'System.Data.SqlClient.SqlConnection'        
       'and 'System.Data.SqlClient.SqlConnection

What does this error really mean?

+1  A: 

Just use a standard For Each loop

For Each cmd In sqlStatements
    cmd.Connection = conn
Next
Adam Robinson
yes, that works but doesn't explain why the list generic forEach has trouble with it, which is ultimately where i'm going with this.
Beta033
A: 

The reason is that Function lambda's in VB.Net (at least for VB9) are required to return a value. The portion of the lambda that reads

cmd.Connection = conn 

is doing a comparison and not an assignment.

This has changed in VB10 since they added statement lambdas:

sqlStatements.ForEach(Sub(cmd) cmd.Connection = conn))    '(my syntax may be off)

As a side note, why do you think the ForEach method would be faster than a conventional For Each loop? Have you actually run into a performance issue?

Chris Dunaway
No, i haven't really tested this, so i'm only really guessing that the List.ForEach implementation would be faster. My thought for this was based on the assumption that ForEach is included in the List generic for a *good* reason and may provide some benefit somewhere. Thanks. this tells me what i need to know.
Beta033