Brian Webster
Brian Webster

Reputation: 30855

Does VB.NET have functionality similar to TSQL's "IN"?

In TSQL..

IF MyVal IN (1, 2, 3, 4, 14) BEGIN ... END

Is there a way to do this in VB.NET?

Is it possible to check for the existence of an integer in a set of integers inline?

Such as:

If MyVal in (1, 2, 3, 4, 14) Then ... End If

Upvotes: 5

Views: 209

Answers (2)

Pero P.
Pero P.

Reputation: 26992

Arrays are an implementation of IEnumerable so with the System.Linq import a shorthand version of Tim Schmelter's answer would be:

{1,2,3,4,14}.Contains(MyVal)

Arrays also have an explicit implementation of IList.Contains, so without LINQ a perhaps less elegant alternative is:

DirectCast({1,2,3,4,14}, IList).Contains(MyVal)

Upvotes: 6

Tim Schmelter
Tim Schmelter

Reputation: 460148

For example List.Contains Method

Dim MyVal = 4
Dim MyValues = {1,2,3,4,5,6,7}.ToList

MyValues.Contains(MyVal)

Or BinarySearch:

MyValues.Sort()
Dim contains = MyValues.BinarySearch(MyVal) > -1

Or Any

MyValues.Any(Function(item)item=MyVal)

Upvotes: 3

Related Questions