Search code examples
c#dictionarycastingienumerabledeferred-execution

Converting IEnumerable<string> to Dictionary


after adding bool distinct to method Splitter and checking if distinct is true the code broke. The quesry now instead of being dictionary is IEnumerable<string>, but whould be 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'. 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;
}

Solution

  • ToDictionary returns what you need. Just return that instead of returning query.

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