为了正常的体验网站,请在浏览器设置里面开启Javascript功能!

如何使用 LINQ 查询来计数指定词在字符串中的出现次数

2017-09-05 3页 doc 14KB 61阅读

用户头像

is_418164

暂无简介

举报
如何使用 LINQ 查询来计数指定词在字符串中的出现次数此示例演示如何使用 LINQ 查询来计数指定词在字符串中的出现次数。请注意,若要执行计数,请先调用 Split 方法来创建词数组。Split 方法存在性能开销。如果对字符串执行的唯一操作是计数词,则您应考虑改用 Matches 或 IndexOf 方法。但是,如果性能不是关键问题,或者您已拆分句子以对其执行其他类型的查询,则使用 LINQ 来计数词或短语同样有意义。 C# class CountWords { static void Main() { string text = @"Historically, the...
如何使用 LINQ 查询来计数指定词在字符串中的出现次数
此示例演示如何使用 LINQ 查询来计数指定词在字符串中的出现次数。请注意,若要执行计数,请先调用 Split 方法来创建词数组。Split 方法存在性能开销。如果对字符串执行的唯一操作是计数词,则您应考虑改用 Matches 或 IndexOf 方法。但是,如果性能不是关键问,或者您已拆分句子以对其执行其他类型的查询,则使用 LINQ 来计数词或短语同样有意义。 C# class CountWords { 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."; string searchTerm = "data"; //Convert the string into an array of words string[] source = text.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries); // Create and execute the query. It executes immediately // because a singleton value is produced. // Use ToLowerInvariant to match "data" and "Data" var matchQuery = from word in source where word.ToLowerInvariant() == searchTerm.ToLowerInvariant() select word; // Count the matches. int wordCount = matchQuery.Count(); Console.WriteLine("{0} occurrences(s) of the search term \"{1}\" were found.", wordCount, searchTerm); // Keep console window open in debug mode Console.WriteLine("Press any key to exit"); Console.ReadKey(); } } /* Output: 3 occurrences(s) of the search term "data" were found. */
/
本文档为【如何使用 LINQ 查询来计数指定词在字符串中的出现次数】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。 本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。 网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。

历史搜索

    清空历史搜索