Using LINQ to check whether a string is a pangram or a palindrome

It's sometimes overlooked that the string class implements the IEnumerable<char> interface and so LINQ methods can be applied directly to it.

This enables some things to be done more succinctly than by using traditional C# code.

For example the following program uses LINQ queries to test whether a string is :

* A pangram (contains all 26 letters of the alphabet); or

* A palindrome (ignoring capitalization and non-letters is the same when reversed).

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string s = "The quick brown fox jumps over the lazy dog";
        Console.WriteLine("It's {0} that \"{1}\" is a pangram", IsPangram(s), s);
        string t = "Doc, note: I dissent. A fast never prevents a fatness. I diet on cod.";
        Console.WriteLine("It's {0} that \"{1}\" is a palindrome", IsPalindrome(t), t);
        string u = "The quick brown fox jumped over the lazy dog";
        Console.WriteLine("It's {0} that \"{1}\" is a pangram", IsPangram(u), u);
        string v = "Madam, I'm Eve";
        Console.WriteLine("It's {0} that \"{1}\" is a palindrome", IsPalindrome(v), v);
        Console.ReadKey();
    }

    static bool IsPangram(string s)
    {
        return s.ToLower().Where(c => Char.IsLetter(c)).GroupBy(c => c).Count() == 26;
    }

    static bool IsPalindrome(string s)
    {
        var s1 = s.ToLower().Where(c => Char.IsLetter(c));
        var s2 = s.ToLower().Reverse().Where(c => Char.IsLetter(c));
        return s1.SequenceEqual(s2);
    }
}

The first two strings, of course, return 'True' and the last two 'False'.

The IsPangram method works by converting the string to lower case, stripping out any non-letter characters and then grouping the remaining letters by each letter. If there are 26 such groups, then the string must be a pangram.

The IsPalindrome method also works by converting the string to lower case and stripping out any non-letter characters. The same is then done for the reverse of the string. If the resulting sequences are equal, then the string  must be a palindome.
Ebook Download
View all
Learn
View all