Art F
Art F

Reputation: 4200

VB.NET Array Contains method does not work

In VB.NET I am trying to determine in a given string exists in a String Array. According to my research the Array has a 'Contains' method that I can use, so the Code looks something like this:

Dim fileTypesZ As String() = {"PDF", "TXT", "DOC", "DOCX", "XLS", "XLSX", "JPG", "JPGE", "BMP", "GIF"}

If (fileTypesZ.Contains(tempTest)) Then

End If

However, VB.NET is saying 'Contains' is not a member of 'System.Array'. Is there another method that I can use?

Upvotes: 6

Views: 19479

Answers (2)

Jason Hughes
Jason Hughes

Reputation: 778

What framework are you working with? I ran this in 4 Full and it worked:

Sub Main()
    Dim fileTypesZ As String() = {"PDF", "TXT", "DOC", "DOCX", "XLS", "XLSX", "JPG", "JPGE", "BMP", "GIF"}

    If (fileTypesZ.Contains("PDF")) Then
        MsgBox("Yay")
    End If
End Sub

Keep in mind array.contains uses equality, so "PDF" works, "PD" does not. You may need to iterate with indexof if you are looking for partial matches.

In that case try: Dim fileTypesZ As String() = {"PDF", "TXT", "DOC", "DOCX", "XLS", "XLSX", "JPG", "JPGE", "BMP", "GIF"}

    If (fileTypesZ.Contains("PD")) Then
        MsgBox("Yay")
    Else
        For i = 0 To fileTypesZ.Length - 1
            If fileTypesZ(i).IndexOf("PD") = 0 Then
                MsgBox("Yay")
            End If
        Next
    End If

Upvotes: 3

Reed Copsey
Reed Copsey

Reputation: 564373

There is no Contains on Array, but there is Enumerable.Contains, which is an extension method that works on arrays.

Make sure to include Imports System.Linq at the top of your file, and that you're referencing System.Core.dll in your project references.

Upvotes: 13

Related Questions