(String) letter frequency in LINQ

How would you determine the frequency of letters in a string using C#? If your mind naturally wandered down some abstruse solution involving loops and 2D arrays containing the ASCII code of the letter and a value for the letter frequency and so on, albeit briefly, and you proffer your skills as a C# developer, then your skills are close approaching being a decade out of date.

Every time I see this type of code construct, and it is very often, I unilaterally make the decision to clean-it-up and do it properly. Properly to me means LINQ. The functionality is bordering on trivial in LINQ too – just look at the code below:

using System;
using System.Linq;

namespace ConsoleApplication963
{
  class Program
  {
    static void Main(string[] args)
    {
      var charFrequencies = from c in "WOODWARD INFORMATICS".ToArray()
                              group c by c into groupFrequencies
                                select groupFrequencies;
      foreach (var c in charFrequencies)
        Console.WriteLine($"Character: {c.Key} Frequency: {c.Count()}");

      Console.ReadLine();
    }
  }
}

LetterFrequencyCountLINQ

Of course LINQ is so much more powerful than I have demonstrated in this small example, and there is a great 101 examples resource available from Microsoft demonstrating so much more too, but for some reason many developers insist on reinventing the wheel with a buggy for loop and arrays and a bunch of if statements for the edge-cases and so on.

Of course the world hasn’t stood still since the availability of LINQ just under a decade ago (I dwell on LINQ as it’s just a hobby horse for me), just look at the proposed C#7 feature list !  Things are and continue to move fast in .NET “land”; it’s frightening.

— Published by Mike, 20:12:12:31 04 September 2016

Leave a Reply