Cannot iterate a collection of anonymous types created from a LINQ query in VB.NET

Well, that’s it, I must have missed something.

Each LINQ example that I have seen for anonymous VB.NET claim types 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 proceed to iterate through the collection (see the example below), I get the error message "Name x not declared."

For Each x in Infos
 ...
Next 

How VB.NET does not understand that Infos is a collection of anonymous types created by LINQ, and wants me to declare "x" as some type. (Won't this defeat the goal of an anonymous type?) I added links to System.Data.Linq and System.Data.DataSetExtensions to my project. Here is what I import with the class:

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

Any ideas?

+3
3

Option Infer On Imports. Option Strict Off , . VB.NET .

+3

vs 20005 vs 2008 vs 2010 Infer Off , , .

vs 2010 2008, vs2005 !! S

+1

Prolly doen't help, but it works for me in 2008 and 2010, maybe you need OptionInfer?

 _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
0
source

Source: https://habr.com/ru/post/1737421/


All Articles