Atari2600
Atari2600

Reputation: 2803

Cannot iterate of a collection of Anonymous Types created from a LINQ Query in VB.NET

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?

Upvotes: 5

Views: 3788

Answers (3)

fedda
fedda

Reputation: 256

I was upgrading from vs 20005 to vs 2008 to vs 2010 the Option Infer Off was turned off, when i turned it on everything worked just fine..

I it is by default turned on on vs 2010 and 2008, but in vs2005 it is not an option!! S

Upvotes: 1

AMissico
AMissico

Reputation: 21684

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.

Upvotes: 5

Eric
Eric

Reputation: 3087

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

Upvotes: 2

Related Questions