如何:查询包含一组指定词语的句子 (LINQ)

此示例演示如何查找文本文件中包含指定的一组单词中每个单词的匹配项的句子。 虽然在此示例中搜索条件数组是硬编码的,但也可以在运行时动态填充此数组。 在此示例中,查询返回包含单词“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``1 方法移除所有重复的单词,然后查询对单词数组和 wordstoMatch 数组执行 Intersect``1 操作。 如果交集的计数与 wordsToMatch 数组的计数相同,则在单词中找到了所有的单词,且返回原始句子。

在对 Split 的调用中,使用标点符号作为分隔符,以从字符串中移除标点符号。 如果您没有这样做,则假如您有一个字符串“Historically,”,该字符串不会与 wordsToMatch 数组中的“Historically”相匹配。 根据源文本中标点的类型,您可能必须使用其他分隔符。

编译代码

  • 创建一个面向 .NET Framework 3.5 版的 Visual Studio 项目。 默认情况下,该项目具有对 System.Core.dll 的引用以及针对 System.Linq 命名空间的 using 指令 (C#) 或 Imports 语句 (Visual Basic)。 在 C# 项目中,添加 System.IO 命名空间的 using 指令。

  • 将此代码复制到您的项目。

  • 按 F5 编译并运行程序。

  • 按任意键退出控制台窗口。

请参见

概念

LINQ 和字符串