Check if strings are anagrams using LINQ–C#

 

The approach in this article shows the use of LINQ to group by array elements and comparing two strings. The underlying algorithm is the traditional approach of sorting the characters in the strings and then comparing the strings. However the more efficient implementation of anagram checking could be done by using hash tables or dictionaries.

   1:  

   2: using System;

   3: using System.Collections.Generic;

   4: using System.Linq;

   5: using System.Text;

   6:  

   7: namespace AnagramCheck

   8: {

   9:     public class AnagramChecker

  10:     {

  11:         public bool IsAnagram(string[] anagrams)

  12:         {

  13:             var orderGroups = anagrams.GroupBy(w => w.Trim(), new AnagramEqualityComparer());

  14:  

  15:             foreach (var group in orderGroups)

  16:             {

  17:                 if (group.Count() == anagrams.Length)

  18:                 {

  19:                     return true;

  20:                 }

  21:             }

  22:             return false;

  23:         }

  24:     }

  25:  

  26:     public class AnagramEqualityComparer : IEqualityComparer<string>

  27:     {

  28:         public bool Equals(string x, string y)

  29:         {

  30:             return getCanonicalString(x) == getCanonicalString(y);

  31:         }

  32:  

  33:         public int GetHashCode(string obj)

  34:         {

  35:             return getCanonicalString(obj).GetHashCode();

  36:         }

  37:  

  38:         private string getCanonicalString(string word)

  39:         {

  40:             char[] wordChars = word.ToCharArray();

  41:             Array.Sort<char>(wordChars);

  42:             return new string(wordChars);

  43:         }

  44:     }

  45: }

Advertisements