Condividi tramite


Procedura: Eseguire una query per le frasi che contengono un set specificato di parole (LINQ) (Visual Basic)

In questo esempio viene illustrato come trovare frasi in un file di testo che contiene corrispondenze per ogni set di parole specificato. Anche se la matrice di termini di ricerca è hard-coded in questo esempio, può anche essere popolata in modo dinamico durante l'esecuzione. In questo esempio la query restituisce le frasi contenenti le parole "Storicamente", "dati" e "integrate".

Esempio

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

La query funziona suddividendo prima il testo in frasi e quindi suddividendo le frasi in una matrice di stringhe che contengono ogni parola. Per ognuna di queste matrici, il Distinct metodo rimuove tutte le parole duplicate e quindi esegue un'operazione Intersect sulla matrice di parole e sulla wordsToMatch matrice. Se il conteggio dell'intersezione è uguale al conteggio della wordsToMatch matrice, tutte le parole sono state trovate nelle parole e viene restituita la frase originale.

Nella chiamata a Split, i segni di punteggiatura vengono usati come separatori per rimuoverli dalla stringa. Se non è stata eseguita questa operazione, ad esempio si potrebbe avere una stringa "Storica", che non corrisponderebbe a "Storicamente" nella wordsToMatch matrice. Potrebbe essere necessario usare separatori aggiuntivi, a seconda dei tipi di punteggiatura trovati nel testo di origine.

Compilare il codice

Creare un progetto di applicazione console di Visual Basic con un'istruzione Imports per lo spazio dei nomi System.Linq.

Vedere anche