c# - 这是使用 LINQ 创建频率表的最佳方式吗?

标签 c# linq

我想编写一个函数来读取文件并计算每个单词出现的次数。假设处理文件读取并生成代表文件中每一行的字符串列表,我需要一个函数来计算每个单词的出现次数。首先,使用 Dictionary<string,int>最好的方法?键是单词,值是该单词出现的次数。

我编写了这个函数,它遍历每一行和一行中的每个单词并构建一个字典:

static IDictionary<string, int> CountWords(IEnumerable<string> lines)
var dict = new Dictionary<string, int>();
foreach (string line in lines)
{
    string[] words = line.Split(' ');
    foreach (string word in words)
    {
        if (dict.ContainsKey(word))
            dict[word]++;
        else
            dict.Add(word, 1);
    }
}

但是,我想以某种方式编写这个函数..功能上,使用 LINQ(因为 LINQ 很有趣,我正在努力提高我的函数式编程技能 :D)我设法想出了这个表达式,但是我'我不确定这是否是功能上最好的方法:

static IDictionary<string, int> CountWords2(IEnumerable<string> lines)
{
    return lines
        .SelectMany(line => line.Split(' '))
        .Aggregate(new Dictionary<string, int>(),
            (dict, word) =>
            {
                if (dict.ContainsKey(word))
                    dict[word]++;
                else
                    dict.Add(word, 1);
                return dict;
            });
}

因此,虽然我有两个可行的解决方案,但我也有兴趣了解解决这个问题的最佳方法是什么。有人了解 LINQ 和 FP 吗?

最佳答案

正如 Tim Robinson 所写,您可以像这样将 GroupByToDictionary 一起使用

    public static Dictionary<string, int> CountWords3(IEnumerable<string> strings)
    {
        return strings.SelectMany(s => s.Split(' ')).GroupBy(w=>w).ToDictionary(g => g.Key, g => g.Count());
    }

关于c# - 这是使用 LINQ 创建频率表的最佳方式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3244994/

相关文章:

c# - datagridview 绑定(bind)到实体不更新数据库

C# LINQ 选择具有相同属性值的对象加入其他属性值

c# - 在 SharpSvn 中,SvnClient.getinfo 的返回值是什么?

c# - 与多个版本的 Word 互操作

c# - FirstOrDefault linq 扩展默认项为 null 即使声明

c# - 在 C# 代码中使用 LINQ 读取 icollection 数据

c# - 如何使用 Linq to Entity Framework 在表达式中使用函数?

c# - 在所有类 List<Object> 中搜索匹配值

c# - 门面模式中的门面类是否需要是静态的?

c# - Task.WhenAny 用于无故障任务