次の方法で共有


方法: 指定した単語セットを含む文を照会する (LINQ) (Visual Basic)

この例では、指定した単語セットごとに一致する文を含むテキスト ファイル内の文を検索する方法を示します。 この例では検索語句の配列はハードコーディングされていますが、実行時に動的に設定することもできます。 この例では、クエリは"履歴"、"データ"、"統合" という単語を含む文を返します。

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

このクエリは、最初にテキストを文に分割してから、各単語を保持する文字列の配列に文を分割することで機能します。 これらの配列ごとに、Distinct メソッドはすべての重複する単語を削除し、クエリは単語配列とIntersect配列に対してwordsToMatch操作を実行します。 交差部分の数が wordsToMatch 配列の数と同じ場合、単語内のすべての単語が見つかり、元の文が返されます。

Splitの呼び出しでは、区切り記号を文字列から削除するために区切り記号として使用されます。 これを行わないと、たとえば、文字列 "Historically" が wordsToMatch 配列の "Historically" と一致しない可能性があります。 ソース テキストで見つかった句読点の種類によっては、追加の区切り記号を使用する必要がある場合があります。

コードをコンパイルする

System.Linq 名前空間の Imports ステートメントを使用して、Visual Basic コンソール アプリケーション プロジェクトを作成します。

こちらも参照ください