简体   繁体   English

转换IEnumerable <string> 到字典

[英]Converting IEnumerable<string> to Dictionary

after adding bool distinct to method Splitter and checking if distinct is true the code broke. 在向方法Splitter添加bool distinct并检查distinct is true ,代码中断了。 The quesry now instead of being dictionary is IEnumerable<string> , but whould be Dictionary<string, int> . 问题现在而不是字典是IEnumerable<string> ,但是应该是Dictionary<string, int> How could it be solved? 怎么可以解决?

This is the error: 这是错误:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.Dictionary'. 无法将类型'System.Collections.Generic.IEnumerable'隐式转换为'System.Collections.Generic.Dictionary'。 An explicit conversion exists (are you missing a cast?) 存在显式转换(您是否错过了演员?)

And the code: 和代码:

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 returns what you need. ToDictionary返回您需要的内容。 Just return that instead of returning query . 只需返回它而不是返回query

return query.GroupBy(word => word)
            .ToDictionary(g => g.Key, g => g.Count());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM