共用方式為


如何:查詢字串中的字元 (LINQ) (Visual Basic)

因為類別 String 會實作泛型 IEnumerable<T> 介面,因此任何字串都可以查詢為字元序列。 不過,這不是 LINQ 的常見用法。 針對複雜的模式比對作業,請使用 類別 Regex

範例

下列範例會查詢字串,以判斷它所包含的數字數。 請注意,第一次執行查詢之後,查詢會「重複使用」。 這是可能的,因為查詢本身不會儲存任何實際的結果。

Class QueryAString

    Shared Sub Main()

        ' A string is an IEnumerable data source.
        Dim aString As String = "ABCDE99F-J74-12-89A"

        ' Select only those characters that are numbers
        Dim stringQuery = From ch In aString
                          Where Char.IsDigit(ch)
                          Select ch
        ' Execute the query
        For Each c As Char In stringQuery
            Console.Write(c & " ")
        Next

        ' Call the Count method on the existing query.
        Dim count As Integer = stringQuery.Count()
        Console.WriteLine(System.Environment.NewLine & "Count = " & count)

        ' Select all characters before the first '-'
        Dim stringQuery2 = aString.TakeWhile(Function(c) c <> "-")

        ' Execute the second query
        For Each ch In stringQuery2
            Console.Write(ch)
        Next

        Console.WriteLine(System.Environment.NewLine & "Press any key to exit")
        Console.ReadKey()
    End Sub
End Class
' Output:
' 9 9 7 4 1 2 8 9
' Count = 8
' ABCDE99F

編譯程式碼

建立一個包含 Imports 語句以使用 System.Linq 命名空間的 Visual Basic 控制台應用程式專案。

另請參閱