使用C# LINQ 查询字符串中某个词出现的次数

 1 public static void CountWords()
 2         {
 3             string text = @"Historically, the world of data and the world of objects" +
 4             @" have not been well integrated. Programmers work in C# or Visual Basic" +
 5             @" and also in SQL or XQuery. On the one side are concepts such as classes," +
 6             @" objects, fields, inheritance, and .NET Framework APIs. On the other side" +
 7             @" are tables, columns, rows, nodes, and separate languages for dealing with" +
 8             @" them. Data types often require translation between the two worlds; there are" +
 9             @" different standard functions. Because the object world has no notion of query, a" +
10             @" query can only be represented as a string without compile-time type checking or" +
11             @" IntelliSense support in the IDE. Transferring data from SQL tables or XML trees to" +
12             @" objects in memory is often tedious and error-prone.";
13             string searchTerm = "data";
14             string[] source = text.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' },
15                 StringSplitOptions.RemoveEmptyEntries);
16             //使用传统fori循环统计
17             int wordCounts = 0;
18             for (int i = 0; i < source.Length; i++)
19             {
20                 if (source[i].ToLowerInvariant()==searchTerm.ToLowerInvariant())
21                 {
22                     wordCounts += 1;
23                 }
24             }
25             //使用LINQ语句查询统计
26             var matchQuery = from word in source
27                              where word.ToUpperInvariant() == searchTerm.ToUpperInvariant()
28                              select word;
29             int wordCount = matchQuery.Count();
30             Console.WriteLine("{0} occurrences(s) of the search term \"{1}\" were found.", wordCounts, searchTerm);
31             Console.WriteLine("{0} occurrences(s) of the search term \"{1}\" were found.",wordCount,searchTerm);
32             Console.ReadKey();
33         }

 

posted on 2020-08-28 15:09  达哥来到  阅读(709)  评论(0)    收藏  举报

导航