How to loop through an IEnumerable in VB.Net

Sherpa 306 Reputation points
2023-06-20T10:25:12.52+00:00
I am getting data from a SQL server in the form of a data table. I am grouping the data by VendorID and concatenate the row data if there are multiple values of the field. This code is given below and it works fine.

Dim dt As DataTable = GetVendorData()
Dim results = From p In dt.AsEnumerable()
              Group p By VendorID = p.Field(Of String)("VenID") Into g = Group
              Select New With {
                  Key .VendorID = VendorID,
                  Key .FundNumber = String.Join(";", From i In g Select i.Field(Of String)("FundNumber")),
                  Key .Statefund = String.Join(";", From i In g Select i.Field(Of String)("Statefund")),
                  Key .State = String.Join(";", From i In g Select i.Field(Of String)("State"))
              }
I tried to loop through and get the individual field data as follows

For Each result As DataRow In results
    Dim x As String = result.Field(Of String)("FundNumber"))
Next
But I am getting the following error.

System.InvalidCastException
HResult=0x80004002
Message=Unable to cast object of type 'VB$AnonymousType_1`4[System.String,System.String,System.String,System.String]' to type 'System.Data.DataRow'

When I tried "For Each result In results", it doesn't even compile. I am getting this error: ""result" is not declared. It may be inaccessible due to its protection level" 
Developer technologies VB
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2023-06-20T10:54:21.18+00:00

    Try something like this:

    For Each result In results
        Dim x As String = result.FundNumber
    
    Next
    
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.