【发布时间】:2015-05-20 13:45:15
【问题描述】:
在将bool distinct 添加到方法Splitter 并检查distinct is true 代码是否损坏后。现在的查询不是字典,而是IEnumerable<string>,但应该是Dictionary<string, int>。怎么可能解决?
这是错误:
无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“System.Collections.Generic.Dictionary”。存在显式转换(您是否缺少演员表?)
还有代码:
private Dictionary<string, int> Splitter(string[] file, bool distinct)
{
var query = file
.SelectMany(i => File.ReadLines(i)
.SelectMany(line => line.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries))
.AsParallel()
.Select(word => word.ToLower())
.Where(word => !StopWords.Contains(word))
.Where(word => !StopWordsPl.Contains(word))
.Where(word => !PopulatNetworkWords.Contains(word))
.Where(word => !word.All(char.IsDigit)));
if (distinct)
{
query = query.Distinct();
}
query.GroupBy(word => word)
.ToDictionary(g => g.Key, g => g.Count());
return query;
}
【问题讨论】:
-
GroupBy 和 ToDictionary 不修改底层对象,您在 query = query.Distinct(); 上方几行正确地做到了这一点;
标签: c# dictionary casting ienumerable deferred-execution