这是使用LINQ创建频率表的最佳方法吗?

guh*_*hou 4 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我想以某种方式编写这个函数..功能上,使用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;
            });
}
Run Code Online (Sandbox Code Playgroud)

因此,虽然我有两个有效的解决方案,但我也有兴趣了解这个问题的最佳方法.有兴趣了解LINQ和FP的人吗?

Yur*_*nko 7

蒂姆·罗宾逊写道:你可以使用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());
    }
Run Code Online (Sandbox Code Playgroud)

  • @Rune FS:这都是LINQ,无论您使用查询理解语法还是扩展方法语法,都是个人偏好的问题.(事实上​​,有些查询只能使用扩展方法语法来表达.你会声称这些查询不是LINQ吗?) (2认同)