学习笔记二--如何:查询包含一组指定单词的句子 (LINQ)

学习笔记二--如何:查询包含一组指定单词的句子 (LINQ)(来自微软MSDN)

此示例演示如何查找文本文件中包含指定的一组单词中每个单词的匹配项的句子。虽然在此示例中搜索条件数组是硬编码的,但也可以在运行时动态填充此数组。在此示例中,查询返回包含单词“Historically”“data”“integrated”的句子。

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

 

C#

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 3.5 版的 Visual Studio 项目。默认情况下,该项目具有对 System.Core.dll 的引用,以及 System.Linq 命名空间的 using 指令 (C#) Imports 语句 (Visual Basic)。在 C# 项目中,添加 System.IO 命名空间的 using 指令。

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

· F5 编译并运行程序。

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值