Friday, June 15, 2012

Compare a string with a list of strings using IEqualityComparer

Problem:
Check if a string appears, partially, on a list of strings.
The List.Contains() method does this, but it only returns complete matches.

Solution:
Create a custom IEQualityComparer.

string[] excludePages = { "string1", "string2", "string3", "str"};

StringEqualityComparer comparer = new StringEqualityComparer();
if (excludePages.Contains("string2", comparer))
{
//string 2 exists in excludePages
}
else
{
//string 2 does not exist in excludePages
}

public class StringEqualityComparer : IEqualityComparer
{
      public bool Equals(string currentListString, string testString)
      {
        return (testString.Contains(currentListString));
      }

      public int GetHashCode(string obj)
      {
        return obj.GetHashCode();
      }
}

Source:
http://www.java2s.com/Code/CSharp/LINQ/ContainswithstringvalueandIEqualityComparer.htm

No comments:

Post a Comment