c# - 如何在 C# (linq) 上创建困难组?

标签 c# linq file grouping

我在文本分析方面遇到了麻烦。 需要计算 .txt 文件中的单词迭代次数 我做到了,但我需要将所有计数放在一起而不分开文件。

如何正确分组重写?

var queryMatchingFiles =
            from file in files
            where file.Extension == ".txt"
            let fileText = File.ReadAllText(file.FullName)
            let matches = Regex.Matches(fileText, searchTerm)
            select new
            {
                matchedValues = from Match match in matches
                                group match by match.Value into grp
                                select new {
                                    key = grp.Key, value = grp.Count()
                                }
            };

最佳答案

您的查询应如下所示:

var queryMatchingFiles =
            from file in files
            where file.Extension == ".txt"
            let fileText = File.ReadAllText(file.FullName)
            from match in Regex.Matches(fileText, searchTerm).Cast<Match>()
            group match by match.Value into grp
            select new
            {
                key = grp.Key,
                value = grp.Count()
            };

创建IEnumerable<Match>来自您可以使用的比赛:

Regex.Matches(fileText, searchTerm).Cast<Match>()

所以你可以写类似 from match in ... 的查询

另一个转换选项是在表达式中显式指定类型:

from Match match in Regex.Matches(fileText, searchTerm)

关于c# - 如何在 C# (linq) 上创建困难组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49519373/

相关文章:

c# - urlencode问题

xml - linq 到 xml : how to select the value from elements

c# - 选择键值对后将字典转换为键值对

javascript - 加载本地文件时出现"Cross origin requests are only supported for HTTP."错误

java - 使用 Play Framework 在后台处理大文件

c# - 结构图 3 中 HybridHttpOrThreadLocalScoped 的等价物是什么?

C# Console.Readkey - 等待特定输入

c# - 使其他类可以访问方法和控件

c# - 实现 LINQ 表达式参数

windows - 这个字符串的含义\\.\c :