12

I have code that ignores common words from user input:

string[] ignored_words = { "the", "and", "I" };

String[] words = UserInput.Split(' ');
foreach (string word in words)
{
    if (!ignored_words.Any(word.Equals))
    {
        // perform actions on desired words only
    }
}

This works great, unless the case is wrong ("THE" as user input will not be caught by the "the" ignored word).

How can I add an IgnoreCase clause to the Equals comparison?

Community
  • 1
  • 1
Travis Heeter
  • 13,002
  • 13
  • 87
  • 129

3 Answers3

23
if (!ignored_words.Any(w => w.Equals(word, StringComparison.CurrentCultureIgnoreCase)))
{
   // ...
}

or with the static String.Equals which has no issues with null values:

if (!ignored_words.Any(w => string.Equals(w, word, StringComparison.CurrentCultureIgnoreCase)))
{
   // ...
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
8

You need to pass a lambda expression:

ignored_words.Any(w => word.Equals(w, StringComparison.OrdinalIgnoreCase)

However, you can make your code much simpler and faster by using more LINQ:

foreach (string word in words.Except(ignored_words, StringComparer.OrdinalIgnoreCase))
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
6

As a more efficient way of doing it:

// note: the exact comparer deserves some thought; cultural? ordinal? invariant?
var ignored_words = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase)
{
    "the", "and", "I"
};

foreach (string word in words)
{
    if (!ignored_words.Contains(word))
    {
        // perform actions on desired words only
    }
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • I actually tried using Contains, but it picked up ignored words within words. For instance, breathe would be ignored because it contained 'the'. – Travis Heeter Apr 20 '15 at 14:55
  • 3
    @TravisHeeter no, that isn't the same `Contains`; what you are describing is `string.Contains`; I am using `HashSet.Contains` - it works completely differently: it would work correctly – Marc Gravell Apr 20 '15 at 15:31