简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM