Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Option Strict and Anonymous Types dont go together?

I have a Linq query that yields anonymous types. However, now I want to work with the parameters of this anonymous type and it does not seem to work.

For Each obj As Object in Query
Dim row As DataRow = obj.parameter
...
Next obj

Now the compiler throws an error on the expression obj.parameter: "Option Strict On disallows late binding". If I understand it right, the compiler doesnt know the parameters of the anonymous type. I tried Option Infer On (and removed As Object), based on Google results, but it didnt help. Which seems to make sense, because it always seems to be a widening conversion to me.

Is there anyway to fix this, or should I just create a custom type?

like image 457
Martao Avatar asked Oct 06 '22 19:10

Martao


1 Answers

The code that declares the anonymous type (i.e. the Select part of your LINQ query) must be in the same method as the the code that uses it and the Query variable's declaration must have an inferred type. You cannot access the properties of an anonymous type after it has been cast to an Object since there is no named type to which you can cast it.

So make sure that your LINQ query (or, at least, the part that Selects into a new anonymous type) is in the same method. E.g.

Dim Query = From prod In products
            Select prod.Name, prod.Price

For Each obj in Query
    Dim name = obj.Name
    ...
Next obj
like image 54
Tim Rogers Avatar answered Oct 10 '22 03:10

Tim Rogers