none
Calculating character frequencies in a word RRS feed

  • Question

  • I am calculating the frequency count of each character in a given string, and placing the result into a Dictionary<T> for subsequent lookup.

    The code below seems to work, but for a few reasons it is causing me some "concern".

    a) The "group characters by characters" clause seems un-intutive - I look at it and think "uhh? -- what is that doing?" ;)
    b) I do not like "var" types! ... what would be the explicit type for the return of the LINQ statement?
    c) The loop to load the results into the Dictionary somehow seems "unnecessary" -  I feel that _somehow_ I could accomplish something similar directly from LINQ ....

    Any help and suggestions would be very welcome!


    private static Dictionary<char, int> getCharFrequency(IEnumerable<char> word) // will accept "string word" too
    {
        // group individual characters in "word" and extract count for each unique character
        var grp = from characters in word
                  group characters by characters
                  into m
                  select new {key = m.Key, count = m.Count()};
    
        // translate "var" (I would MUCH prefer to use an explicit type) into a Directory object       
        Dictionary<char, int> charFrequency = new Dictionary<char, int>();
    
        foreach (var g in grp)
        {
            charFrequency.Add(g.key, g.count);
        }
    
        return charFrequency;
    }
    Wednesday, April 22, 2009 5:28 PM

Answers

  • var frequency = (from c in word group c by c).ToDictionary(g => g.Key, g => g.Count());

     


    Wayward LINQ Lacky
    • Marked as answer by jcliff Thursday, April 23, 2009 5:04 AM
    Wednesday, April 22, 2009 10:27 PM
    Moderator

All replies

  • IEnumerable<KeyValuePair<char, int>> pairs = from c in word
                  group c by c
                  into m
                  select new KeyValuePair<char, int>(m.Key, m.Count());
    
         
        Dictionary<char, int> charFrequency = new Dictionary<char, int>(pairs.Count());
    
        foreach (KeyValuePair<char, int> kvp)
        {
            charFrequency.Add(kvp.Key, kvp.Value);
        }
    

    MVP XML My blog
    Wednesday, April 22, 2009 7:25 PM
  • var frequency = (from c in word group c by c).ToDictionary(g => g.Key, g => g.Count());

     


    Wayward LINQ Lacky
    • Marked as answer by jcliff Thursday, April 23, 2009 5:04 AM
    Wednesday, April 22, 2009 10:27 PM
    Moderator
  • Thanks so much guys!

    LINQ is slowly beginning to sinq in !
    Thursday, April 23, 2009 5:05 AM