Notitie
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen u aan te melden of de directory te wijzigen.
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen de mappen te wijzigen.
In dit voorbeeld ziet u hoe u een LINQ-query gebruikt om het aantal exemplaren van een opgegeven woord in een tekenreeks te tellen. Houd er rekening mee dat om te tellen, eerst de Split methode wordt aangeroepen om een array met woorden te maken. Er zijn prestatiekosten voor de Split methode. Als de enige bewerking op de tekenreeks het tellen van de woorden is, moet u overwegen om in plaats daarvan de Matches of IndexOf methode te gebruiken. Als de prestaties echter geen kritiek probleem zijn of als u de zin al hebt gesplitst om andere typen query's erop uit te voeren, is het zinvol om LINQ te gebruiken om ook de woorden of woordgroepen te tellen.
Voorbeeld
Class CountWords
Shared Sub Main()
Dim text As String = "Historically, the world of data and the world of objects" &
" have not been well integrated. Programmers work in C# or Visual Basic" &
" and also in SQL or XQuery. On the one side are concepts such as classes," &
" objects, fields, inheritance, and .NET Framework APIs. On the other side" &
" are tables, columns, rows, nodes, and separate languages for dealing with" &
" them. Data types often require translation between the two worlds; there are" &
" different standard functions. Because the object world has no notion of query, a" &
" query can only be represented as a string without compile-time type checking or" &
" IntelliSense support in the IDE. Transferring data from SQL tables or XML trees to" &
" objects in memory is often tedious and error-prone."
Dim searchTerm As String = "data"
' Convert the string into an array of words.
Dim dataSource As String() = text.Split(New Char() {" ", ",", ".", ";", ":"},
StringSplitOptions.RemoveEmptyEntries)
' Create and execute the query. It executes immediately
' because a singleton value is produced.
' Use ToLower to match "data" and "Data"
Dim matchQuery = From word In dataSource
Where word.ToLowerInvariant() = searchTerm.ToLowerInvariant()
Select word
' Count the matches.
Dim count As Integer = matchQuery.Count()
Console.WriteLine(count & " occurrence(s) of the search term """ &
searchTerm & """ were found.")
' Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.")
Console.ReadKey()
End Sub
End Class
' Output:
' 3 occurrence(s) of the search term "data" were found.
De code compileren
Maak een Visual Basic-consoletoepassingsproject met een Imports
instructie voor de System.Linq-naamruimte.