我想编写一个函数来读取文件并计算每个单词出现的次数。假设处理文件读取并生成代表文件中每一行的字符串列表,我需要一个函数来计算每个单词的出现次数。首先,使用 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 所写,您可以像这样将 GroupBy
与 ToDictionary
一起使用
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/