次の方法で共有


方法 : 指定された単語のセットを含む文章を照会する (LINQ)

更新 : 2007 年 11 月

この例では、指定された単語のセットの各単語に一致する部分を含む文章をテキスト ファイル内で検索する方法を示します。この例では、検索条件の配列がハードコーディングされていますが、実行時に検索条件を動的に指定できるようにする方法もあります。この例のクエリでは、"Historically"、"data"、および "integrated" という各単語を含む文章が返されます。

使用例

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

このクエリでは、最初にテキストを複数の文章に分割し、次にそれらの文章を分割して、各単語を含む文字列の配列を作成します。これらの配列のそれぞれについて、Distinct メソッドで重複する単語をすべて削除した後、クエリによって単語の配列と wordstoMatch 配列の Intersect 操作を実行します。共通部分の数と wordsToMatch 配列の単語数が同じ場合は、指定された単語のすべてが一致したことになるため、元の文章が返されます。

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

コードのコンパイル方法

  • .NET Framework Version 3.5 を対象とする Visual Studio プロジェクトを作成します。プロジェクトには、System.Core.dll への参照と、System.Linq 名前空間に対する using ディレクティブ (C#) または Imports ステートメント (Visual Basic) が既定で含まれます。C# プロジェクトでは、System.IO 名前空間に対する using ディレクティブを追加します。

  • このコードをプロジェクト内にコピーします。

  • F5 キーを押して、プログラムをコンパイルおよび実行します。

  • 任意のキーを押して、コンソール ウィンドウを終了します。

参照

概念

LINQ と文字列