GroupBy

Isogram
Isogram in C#
using System.Linq;

public static class Isogram
{
    public static bool IsIsogram(string word)
    {
        return word.ToLower().Where(Char.IsLetter).GroupBy(ltr => ltr).All(ltr_grp => ltr_grp.Count() == 1);
    }
}

The steps for this solution are

  • ToLower produces a new string with its characters changed to lower case. That string is chained to Where.
  • Where uses IsLetter to filter the string so only Unicode letters get put into a List. So no hyphens nor apostrophes (nor anything else that is not a letter) will make it into the List.
  • GroupBy groups each letter into its own group.
  • All uses Count to return whether all groups of letters have only one letter in its group.

If any group has a count of more than 1 for its letter, the word is not an isogram.

  • The word Bravo is an isogram because all five groups of letters has a count of 1.
  • The word Alpha is not an isogram because a is considered to repeat A, so it has only four groups of letters, and the group for a has a count of 2.

Shortening

When the body of a function is a single expression, the function can be implemented as an expression-bodied member, like so

public static bool IsIsogram(string word) =>
    word.ToLower().Where(Char.IsLetter).GroupBy(ltr => ltr).All(ltr_grp => ltr_grp.Count() == 1);

or

public static bool IsIsogram(string word) => word.ToLower().Where(Char.IsLetter).GroupBy(ltr => ltr).All(ltr_grp => ltr_grp.Count() == 1);
24th Apr 2024 · Found it useful?