Check if a String is a Palindrome with LINQ

Programming LINQ C#

You can use the power of LINQ to solve problems in just a few lines of code instead of "inventing your own algorithms" - which will lead to much cleaner code of course.

Let's look at following C# Console App that has a method IsPalindrome().  This method checks whether a given string is a palindrome (=a word, sentence, verse, or even number that reads the same backward or forward) or not:

using System;

string testString = "A man, a plan, a canal: Panama!";
bool result = IsPalindrome(testString);
Console.WriteLine($"Is the string \"{testString}\" a palindrome? {result}");

static bool IsPalindrome(string input)
{
  if (string.IsNullOrEmpty(input))
      return false;

    int left = 0;
    int right = input.Length - 1;

    while (left < right)
    {
      // Ignore non-alphanumeric characters
      while (left < right && !char.IsLetterOrDigit(input[left]))
            left++;

      while (left < right && !char.IsLetterOrDigit(input[right]))
          right--;

// Comparison char by char & ignoring case
      if (char.ToLower(input[left]) != char.ToLower(input[right]))
          return false;

        left++;
        right--;
    }
    return true;
}

While this code above works it could be written in a much more elegant way.  And besides, execution performance will also increase (although honestly that's not such a concern in this particular use case since we're dealing with a few words).

When we have to check if a given string reads the same back or forward  we have to obviously reverse the string. Thankfully we have a Reverse() method in LINQ.  In order to reverse a string, we simply can use

string input = "Hello World!";
string reversed = new string(input.Reverse().ToArray());

which enables us to skip all this left/right shuffling done before.  Using SequenceEqual() method from LINQ in order to compare the original sequence with the reversed one, we can break our code down to this slick version:

using System;
using System.Text.RegularExpressions;

string testString = "A man, a plan, a canal: Panama!";
bool result = IsPalindrome(testString);
Console.WriteLine($"Is the string \"{testString}\" a palindrome? {result}");

static bool IsPalindrome(string input)
{
    if (string.IsNullOrEmpty(input))
        return false;

  // Ignore non-alphanumeric characters and case
  input = Regex.Replace(input.ToLower(), "[^a-z0-9]", "");

  string reversed = new string(input.Reverse().ToArray());   // reversed sequence
  return input.SequenceEqual(reversed);                     // compare & return result
}