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 newstring
with its characters changed to lower case. That string is chained toWhere
. -
Where
uses IsLetter to filter thestring
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 theList
. -
GroupBy
groups each letter into its own group. -
All
usesCount
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 of1
. - The word
Alpha
is not an isogram becausea
is considered to repeatA
, so it has only four groups of letters, and the group fora
has 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);
11th Dec 2024
·
Found it useful?