Converting IEnumerable<string> to Dictionary
Asked Answered
J

1

5

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;
}
Jac answered 20/5, 2015 at 13:45 Comment(1)
GroupBy and ToDictionary do not modify underlying object, you do it correctly few lines above query = query.Distinct();Groundwork
T
16

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

return query.GroupBy(word => word)
            .ToDictionary(g => g.Key, g => g.Count());
Tidbit answered 20/5, 2015 at 13:46 Comment(3)
@YuvalItzchakov i know!Tidbit
It's worth pointing out that the distinct code now only has the effect of making the count value here always 1. I find it unlikely that this was intended, and don't see any use for distinct.Weariless
@Ken'ichiMatsuyama here's a more efficient way to do it, then: .ToDictionary(g => g.Key, g => distinct ? 1 : g.Count());. Actually calling Distinct is unnecessary work for both the computer and the human code-reader.Weariless

© 2022 - 2024 — McMap. All rights reserved.