转换IEnumerable< string>字典
本文关键字:字典 string IEnumerable 转换 | 更新日期: 2023-09-27 17:50:17
在将bool distinct
添加到方法Splitter并检查distinct is true
是否代码破裂后。现在的查询不是字典,而是IEnumerable<string>
,而应该是Dictionary<string, int>
。如何解决这个问题?
错误:
不能隐式转换类型"System.Collections.Generic"。到"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;
}
ToDictionary
返回您需要的内容。只要返回那个,而不是返回query
。
return query.GroupBy(word => word)
.ToDictionary(g => g.Key, g => g.Count());