views:

275

answers:

2

Ok everyone, I must be missing something here.

Every LINQ example I have seen for VB.NET anonymous types claims I can do something like this:

                    Dim Info As EnumerableRowCollection = pDataSet.Tables(0).AsEnumerable
                    Dim Infos = From a In Info _
                        Select New With {.Prop1 = a("Prop1"), .Prop2 = a("Prop2"), .Prop3 = a("Prop3") }

Now when I go to iterate through the collection(see example below), I get an error that says "Name "x" is not declared.

For Each x in Infos
 ...
Next 

It's like VB.NET doesn't understand that Infos is a collection of anonymous types created by LINQ and wants me to declare "x" as some type. (Wouldn't this defeat the purpose of an anonymous type?) I have added the references to System.Data.Linq and System.Data.DataSetExtensions to my project. Here is what I am importing with the class:

Imports System.Linq
Imports System.Linq.Enumerable
Imports System.Linq.Queryable
Imports System.Data.Linq

Any ideas?

A: 

Prolly doen't help, but this works for me in 2008 & 2010, maybe you need OptionInfer on?

 _people.Add(New Person With {.Name = "P1", .Age = 1, .BDay = Now})
        _people.Add(New Person With {.Name = "P2", .Age = 2, .BDay = Now})
        _people.Add(New Person With {.Name = "P3", .Age = 3, .BDay = Now})
        _people.Add(New Person With {.Name = "P4", .Age = 4, .BDay = Now})
        Dim infos = From x In _people _
                    Select New With {.anonName = x.Name, .anonAge = x.Age}

        For Each anon In infos
            Debug.Print("anonName=" + anon.anonName + " anonAge=" + anon.anonAge.ToString)
        Next
Eric
A: 

You need to add Option Infer On before the Imports statements. You may also need Option Strict Off depending on if you use it or not. This allows VB.NET to infer the anonymous type.

AMissico
While having `Option Infer Off` would make the `For Each` line fail, it would also make the `Dim Infos = ...` line fail, unless `Option Strict` is also off.
Gideon Engelberth