NealR
NealR

Reputation: 10709

Equivalent of var in Visual Basic to use in For Each Loop

I need to run some code in Visual Basic that is the equivalent to this in C#:

for(var item in removeRows)
{
   two.ImportRow(item);
}

I know that the closest you can come to declaring "var" in VB is basically

Dim something =

However, how would you do this in a foreach loop?

Upvotes: 4

Views: 3976

Answers (8)

Dave Doknjas
Dave Doknjas

Reputation: 6542

With Option Infer On, you can leave off the "As ..." and the type will be inferred. With Option Infer Off, if you leave off the type, the "Object" type will be assumed.

Upvotes: 4

Jim Wooley
Jim Wooley

Reputation: 10418

As others have mentioned the As Type is option IF you have option infer on. I suspect your project has option infer turned off (which was the default when importing existing projects started in .Net 2.0). Turn Option Infer On at the top of the project file or in the project's Compile settings.

Option Infer On
'' This works:
For Each item In removeRows
   two.ImportRow(item)
Next

Option Infer Off
'' Requires:
For Each item As DataRow In removeRows
   '' I'm assuming the strong type here. Object will work with Option Strict Off
   two.ImportRow(item)
Next

Upvotes: 3

John Koerner
John Koerner

Reputation: 38087

You don't need the "as" in vb:

For Each p  In Process.GetProcesses()
    Debug.WriteLine(p.ProcessName)
Next

Upvotes: 0

paulsm4
paulsm4

Reputation: 121881

Something like this:

   Dim siteName As String
   Dim singleChar As Char
   siteName = "HTTP://NET-INFORMATIONS.COM"
   For Each singlechar In siteName
        two.ImportRow(singleChar);
   Next

Upvotes: 0

Aghilas Yakoub
Aghilas Yakoub

Reputation: 29000

You can try (With Object), type is optional

For Each item As Object In removeRows
    two.ImportRow(item)
Next

Upvotes: 0

Pit Digger
Pit Digger

Reputation: 9800

    For Each item As Object in removerows
       two.ImportRow(item)
    Next

Omitting the type in VB.NET (VB9) will implicitly type the variable.

Upvotes: 1

Bgi
Bgi

Reputation: 2494

In the For Each documentation it is written that the As Type is optional.

So

For Each row in removeRows
...
Next

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564891

You would just use:

For Each item In removeRows
    two.ImportRow(item)
Next

The As datatype specification in VB is optional. See For Each documentation for details.

Upvotes: 5

Related Questions