Dela via


Anvisningar: Fråga efter meningar som innehåller en angiven uppsättning ord (LINQ) (Visual Basic)

Det här exemplet visar hur du hittar meningar i en textfil som innehåller matchningar för var och en av en angiven uppsättning ord. Även om matrisen med söktermer är hårdkodad i det här exemplet kan den också fyllas i dynamiskt vid körning. I det här exemplet returnerar frågan de meningar som innehåller orden "Historically", "data" och "integrated".

Exempel

Class FindSentences

    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."

        ' Split the text block into an array of sentences.
        Dim sentences As String() = text.Split(New Char() {".", "?", "!"})

        ' Define the search terms. This list could also be dynamically populated at run time
        Dim wordsToMatch As String() = {"Historically", "data", "integrated"}

        ' Find sentences that contain all the terms in the wordsToMatch array
        ' Note that the number of terms to match is not specified at compile time
        Dim sentenceQuery = From sentence In sentences
                            Let w = sentence.Split(New Char() {" ", ",", ".", ";", ":"},
                                                   StringSplitOptions.RemoveEmptyEntries)
                            Where w.Distinct().Intersect(wordsToMatch).Count = wordsToMatch.Count()
                            Select sentence

        ' Execute the query
        For Each str As String In sentenceQuery
            Console.WriteLine(str)
        Next

        ' Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.")
        Console.ReadKey()
    End Sub

End Class
' Output:
' Historically, the world of data and the world of objects have not been well integrated

Frågan fungerar genom att först dela upp texten i meningar och sedan dela upp meningarna i en matris med strängar som innehåller varje ord. För var och en av dessa matriser Distinct tar metoden bort alla duplicerade ord och sedan utför frågan en Intersect åtgärd på ordmatrisen och matrisen wordsToMatch . Om antalet skärningspunkter är samma som antalet i matrisen wordsToMatch hittades alla ord i orden och den ursprungliga meningen returneras.

I anropet till Splitanvänds skiljetecken som avgränsare för att ta bort dem från strängen. Om du inte gjorde det kan du till exempel ha en sträng "Historically" som inte matchar "Historically" i matrisen wordsToMatch . Du kan behöva använda ytterligare avgränsare, beroende på vilka typer av skiljetecken som finns i källtexten.

Kompilera koden

Skapa ett Visual Basic-konsolprogramprojekt med en Imports instruktion för System.Linq-namnområdet.

Se även