5

在 VB.NET 中,我试图确定给定字符串是否存在于字符串数组中。根据我的研究,数组有一个我可以使用的“包含”方法,所以代码看起来像这样:

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

If (fileTypesZ.Contains(tempTest)) Then

End If

但是,VB.NET 说“包含”不是“System.Array”的成员。我可以使用另一种方法吗?

4

2 回答 2

12

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.

于 2013-09-27T17:46:58.443 回答
2

你正在使用什么框架?我在 4 Full 中运行它并且它有效:

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

请记住,array.contains 使用相等,因此“PDF”有效,“PD”无效。如果您正在寻找部分匹配,您可能需要使用 indexof 进行迭代。

在这种情况下尝试: 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
于 2013-09-27T20:35:15.263 回答