Mayron
Mayron

Reputation: 2394

LINQ expression using a previously defined variable

I am trying to create a LINQ expression that converts a value to another value type (in this case a string to an integer) and then add converted values to a list.

The problem is that it shows this error:

Range Variable 'newValue' hides a variable in an enclosing block or a range variable previously defined in the query expression

It's complaining because newValue is defined outside of the LINQ expression but I need it there else everything shows up in red as undefined.

How can I fix this?

Dim newValue As Integer

Dim newList As List(Of Integer) = (
        From value In valueList
        Where Integer.TryParse(value, newValue)
        Select newValue).ToList()

enter image description here

Upvotes: 0

Views: 190

Answers (1)

NetMage
NetMage

Reputation: 26907

VB has some funny ideas about LINQ query syntax.

You can switch to lambda syntax or put parentheses around the variable in the Select:

Dim newList = valueList.Where(Function(value) Integer.TryParse(value, newValue)).Select(Function(value) newValue).ToList()

Dim newList As List(Of Integer) = (
        From value In valueList
        Where Integer.TryParse(value, newValue)
        Select (newValue)).ToList()

Upvotes: 2

Related Questions