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
-
ToLowerproduces a newstringwith its characters changed to lower case. That string is chained toWhere. -
Whereuses IsLetter to filter thestringso 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 theList. -
GroupBygroups each letter into its own group. -
AllusesCountto 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
Bravois an isogram because all five groups of letters has a count of1. - The word
Alphais not an isogram becauseais considered to repeatA, so it has only four groups of letters, and the group forahas a count of2.
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);
4th Sep 2024
·
Found it useful?