Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring case in Linq.Any, C#

Tags:

c#

linq

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?

like image 664
Travis Heeter Avatar asked Apr 20 '15 14:04

Travis Heeter


2 Answers

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)))
{
   // ...
}
like image 109
Tim Schmelter Avatar answered Nov 17 '22 05:11

Tim Schmelter


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))
like image 8
SLaks Avatar answered Nov 17 '22 04:11

SLaks