Sdílet prostřednictvím


Postupy: Vytvoření dotazu na věty obsahující zadanou množinu slov (LINQ)

Tento příklad ukazuje, jak najít věty v textovém souboru, která obsahují položky pro každou zadanou sadu slov.Pole hledané termíny je pevně v tomto příkladu, ji může také naplnit dynamicky za běhu.V tomto příkladu vrátí dotaz vět, které obsahují slova "Historicky", "data" a "integrované".

Příklad

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
*/

Dotaz funguje tak, že nejprve rozdělení textu do věty a potom rozdělení do pole řetězců, které obsahují jednotlivá slova, věty.Pro každý z těchto polí Distinct``1 metoda odstraní všechny duplicitní slova a potom provede dotaz Intersect``1 operace na pole aplikace word a wordstoMatch pole.Pokud počet průsečík je stejný jako počet wordsToMatch matice, všechna slova, které byly nalezeny v slova a je vrácena původní větu.

Při volání Split, interpunkční znaménka jsou použity jako oddělovače k jejich odebrání z řetězce.Pokud jste neučinili, například řetězec může mít "Historicky", které není odpovídají v "Historicky" wordsToMatch pole.Budete muset použít další oddělovače, v závislosti na typech interpunkce v textu zdroje.

Probíhá kompilace kódu

  • Vytvoření Visual Studio projektu, který se zaměřuje .NET Framework verze 3.5.Ve výchozím nastavení projektu odkazuje na System.Core.dll a using směrnice (C#) nebo Imports prohlášení (Visual Basic) pro obor názvů System.Linq.V jazyce C# projekty, přidejte using směrnice pro obor názvů System.IO.

  • Zkopírujte tento kód do projektu.

  • Stisknutím klávesy F5 sestavit a spustit program.

  • Stisknutím libovolné klávesy uzavřete okno konzoly.

Viz také

Koncepty

LINQ a řetězce