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
编译代码
创建 Visual Basic 控制台应用程序项目,其中包含 Imports
System.Linq 命名空间的语句。