Compartilhar via


Como: consultar as sentenças que contêm um conjunto especificado de palavras (LINQ)

Este exemplo mostra como localizar sentenças em um arquivo de texto que contêm correspondências para cada um de um conjunto especificado de palavras.Embora a matriz dos termos de pesquisa é embutido neste exemplo, ele poderia também ser preenchido dinamicamente em tempo de execução.Neste exemplo, a consulta retorna as frases que contenham as palavras "Historicamente", "dados" e "integrado".

Exemplo

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 runtime
        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
class FindSentences
{
    static void Main()
    {
        string text = @"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.
        string[] sentences = text.Split(new char[] { '.', '?', '!' });

        // Define the search terms. This list could also be dynamically populated at runtime.
        string[] wordsToMatch = { "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.
        var 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. Note that you can explicitly type
        // the iteration variable here even though sentenceQuery
        // was implicitly typed. 
        foreach (string str in sentenceQuery)
        {
            Console.WriteLine(str);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
}
/* Output:
Historically, the world of data and the world of objects have not been well integrated
*/

A consulta funciona primeiro dividir o texto em sentenças e, em seguida, dividindo as sentenças em uma matriz de seqüências de caracteres que mantenha a tecla de cada palavra.Para cada um desses conjuntos, o Distinct método remove todas as palavras duplicadas e executa a consulta um Intersect operação em que a matriz do word e o wordstoMatch array.Se a contagem de interseção é o mesmo que a contagem da wordsToMatch array, todas as palavras foram encontradas nas palavras e a sentença original é retornada.

Na chamada para Split, as marcas de pontuação são usadas como separadores para removê-los da seqüência de caracteres.Se você não fez isso, por exemplo, você poderia ter uma seqüência de caracteres "Historicamente", que não corresponderia "Historicamente" na wordsToMatch array.Talvez você precise usar separadores adicionais, dependendo dos tipos de pontuação encontrado no texto de origem.

Compilando o código

  • Criar um Visual Studio o projeto que se destina a .NET Framework versão 3.5.Por padrão, o projeto tem uma referência a System.Core.dll e um using diretiva (C#) ou Imports instrução (Visual Basic) para o namespace System. LINQ.No C# projetos, adicione um using diretriz para o namespace System. IO.

  • Copie este código para seu projeto.

  • Pressione F5 para compilar e executar o programa.

  • Pressione qualquer tecla para sair da janela do console.

Consulte também

Conceitos

LINQ e seqüências de caracteres