4

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;
}
  • 2
    GroupBy and ToDictionary do not modify underlying object, you do it correctly few lines above query = query.Distinct(); – Andrey May 20 '15 at 13:47

1 Answers1

15

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

return query.GroupBy(word => word)
            .ToDictionary(g => g.Key, g => g.Count());
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • @YuvalItzchakov i know! – Daniel A. White May 20 '15 at 13:57
  • 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`. – Tim S. May 20 '15 at 13:58
  • 1
    @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. – Tim S. May 20 '15 at 14:28